I am new in fragments. I am having a fragment which has 3 sides. In my login activity it passes all data by sharedpreference. When I get into my fragment home, it displays the data by the shared preference. In my other part of the fragment is the edit profile. It must retrieve the data I have and put into the set text.
Here is my SideProfileFragment
public class SideProfileFragment extends Fragment{
private static final String TAG = SideProfileFragment.class.getSimpleName();
public EditText name, birthDate, address, occupation, gender, number;
SessionManager sessionManager;
String getId;
private static String URL_READ = "http://isalonbyageeks.000webhostapp.com/readDetail.php";
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_sideprofile, container, false);
return view;
}
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
sessionManager = new SessionManager(getActivity());
sessionManager.checkLogin();
name = (EditText) getActivity().findViewById(R.id.userName);
birthDate = (EditText) getActivity().findViewById(R.id.userBirthDate);
address = (EditText) getActivity().findViewById(R.id.userAddress);
occupation = (EditText) getActivity().findViewById(R.id.userOccupation);
gender = (EditText) getActivity().findViewById(R.id.userGender);
number = (EditText) getActivity().findViewById(R.id.userNumber);
HashMap<String, String> user = sessionManager.getUserDetail();
getId = user.get(sessionManager.ID);
}
private void getUserDetail(){
final ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Loadingws...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_READ,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
Log.i(TAG, response);
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
JSONArray jsonArray = jsonObject.getJSONArray("read");
if(success.equals("1")){
for(int i = 0; 1 < jsonArray.length();i++){
JSONObject object = jsonArray.getJSONObject(i);
String strName = object.getString ("name");
String strNumber = object.getString("phone_number");
String strGender = object.getString("gender");
String strAddress = object.getString("address");
String strOccupation = object.getString("occupation");
String strBirthDate = object.getString("birth_date");
name.setText(strName);
birthDate.setText(strBirthDate);
address.setText(strAddress);
number.setText(strNumber);
gender.setText(strGender);
occupation.setText(strOccupation);
}
}
} catch (JSONException e) {
e.printStackTrace();
progressDialog.dismiss();
Toast.makeText(getActivity(),"Error Reading Detail" +e.toString(), Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(getActivity(),"Error Reading Detail" +error.toString(), Toast.LENGTH_LONG).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError{
Map<String, String> params = new HashMap<>();
params.put("id", getId);
return super.getParams();
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
#Override
public void onResume(){
super.onResume();
getUserDetail();
}
}
I tried setting the text with a sample "text" inside the oncreated view and it worked. but when I put the set text inside the function getUserDetails it did not do anything, my sideprofile just showed blank edit texts.
PS I tried to put a sample text inside the set text of the function, but still nothing went out.
Edit
This is the XML code of sideprofilefragment that I have. Everything seems so fine!
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/black"
xmlns:app="http://schemas.android.com/apk/res-auto">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/settingImageEdit"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:src="#drawable/defaultpic"/>
<TextView
android:id="#+id/editProfilePicture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/settingImageEdit"
android:layout_marginTop="7dp"
android:text="Edit Photo"
android:layout_centerHorizontal="true"
android:textColor="#color/white"
android:textSize="12sp" />
<AutoCompleteTextView
android:id="#+id/userName"
android:layout_width="300dp"
android:layout_height="35dp"
android:layout_below="#+id/editProfilePicture"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:background="#drawable/rounded_white"
android:drawableLeft="#drawable/ic_user_icon"
android:drawablePadding="5dp"
android:hint="Email/Username"
android:paddingStart="10dp"
android:paddingLeft="10dp"
android:textSize="14sp" />
<AutoCompleteTextView
android:id="#+id/userNumber"
android:layout_width="300dp"
android:layout_height="35dp"
android:layout_below="#+id/userName"
android:layout_marginTop="8dp"
android:layout_centerHorizontal="true"
android:background="#drawable/rounded_white"
android:drawableLeft="#drawable/ic_phone"
android:drawablePadding="5dp"
android:hint="Phone Number"
android:inputType="number"
android:paddingStart="10dp"
android:paddingLeft="10dp"
android:textSize="14sp" />
<AutoCompleteTextView
android:id="#+id/userOccupation"
android:layout_width="300dp"
android:layout_height="35dp"
android:layout_below="#+id/userNumber"
android:layout_marginTop="8dp"
android:layout_centerHorizontal="true"
android:background="#drawable/rounded_white"
android:drawableLeft="#drawable/ic_occupation"
android:drawablePadding="5dp"
android:hint="Occupation"
android:paddingStart="10dp"
android:paddingLeft="10dp"
android:textSize="14sp" />
<AutoCompleteTextView
android:id="#+id/userAddress"
android:layout_width="300dp"
android:layout_height="35dp"
android:layout_below="#+id/userOccupation"
android:layout_marginTop="8dp"
android:background="#drawable/rounded_white"
android:drawableLeft="#drawable/ic_address"
android:layout_centerHorizontal="true"
android:drawablePadding="5dp"
android:hint="Address"
android:paddingStart="10dp"
android:paddingLeft="10dp"
android:textSize="14sp"
tools:ignore="RtlSymmetry" />
<AutoCompleteTextView
android:id="#+id/userGender"
android:layout_width="150dp"
android:layout_height="35dp"
android:layout_below="#+id/userAddress"
android:layout_alignStart="#+id/userName"
android:layout_alignLeft="#+id/userName"
android:layout_marginStart="0dp"
android:layout_marginLeft="0dp"
android:layout_marginTop="8dp"
android:background="#drawable/rounded_white"
android:drawableLeft="#drawable/ic_gender"
android:drawablePadding="5dp"
android:hint="Gender"
android:paddingStart="10dp"
android:paddingLeft="10dp"
android:textSize="14sp" />
<EditText
android:id="#+id/userBirthDate"
android:layout_width="170dp"
android:layout_height="34dp"
android:layout_below="#+id/userGender"
android:layout_alignStart="#+id/userGender"
android:layout_alignLeft="#+id/userGender"
android:layout_marginStart="0dp"
android:layout_marginLeft="0dp"
android:layout_marginTop="8dp"
android:background="#drawable/rounded_white"
android:drawableLeft="#drawable/ic_calendar"
android:drawablePadding="5dp"
android:ems="10"
android:hint="Tap to set Birthdate"
android:inputType="date"
android:paddingLeft="5dp"
android:textSize="14sp" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/userAddress"
android:layout_alignParentBottom="true"
android:layout_marginTop="101dp"
android:layout_centerHorizontal="true"
android:layout_marginBottom="70dp"
android:text="Save Edit" />
</RelativeLayout>
What should I really need to change? I tried to put
name.setText("sample");
inside the onviewcreated, it worked. but when in the function, it didnt.
Your views will be contained within the view passed in
onViewCreated(View view, #Nullable Bundle savedInstanceState)
and not your activity, so you need to use it to refer your variables.
name = (EditText) view.findViewById(R.id.userName);
change it as above for all views.
Replace all getActivity().findViewById() to view.findViewById()
name = (EditText) view.findViewById(R.id.userName);
replace for all views
also when you receive the result from http request you need to run UI operations on UI thread.
example :
getActivity().runOnUiThread(new Runnable() {
progressDialog.dismiss();
Log.i(TAG, response);
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
JSONArray jsonArray = jsonObject.getJSONArray("read");
if(success.equals("1")){
for(int i = 0; 1 < jsonArray.length();i++){
JSONObject object = jsonArray.getJSONObject(i);
String strName = object.getString ("name");
String strNumber = object.getString("phone_number");
String strGender = object.getString("gender");
String strAddress = object.getString("address");
String strOccupation = object.getString("occupation");
String strBirthDate = object.getString("birth_date");
name.setText(strName);
birthDate.setText(strBirthDate);
address.setText(strAddress);
number.setText(strNumber);
gender.setText(strGender);
occupation.setText(strOccupation);
}
}
} catch (JSONException e) {
e.printStackTrace();
progressDialog.dismiss();
Toast.makeText(getActivity(),"Error Reading Detail" +e.toString(), Toast.LENGTH_LONG).show();
}
}
});
1) replace all the getActivity().findViewById() by view.findViewById()
2) you need to handle the setting of the UI in another thread
try {
Handler uiHandler = new Handler(Looper.getMainLooper());
uiHandler.post(new Runnable() {
#Override
public void run() {
name.setText(strName);
birthDate.setText(strBirthDate);
address.setText(strAddress);
number.setText(strNumber);
gender.setText(strGender);
occupation.setText(strOccupation);
}
});
} catch (Exception e) {
Log.i("bugs", e.getMessage());
e.printStackTrace();
}
3) If the problem persists, also give android:layout_height="match_parent" to all
the TextViews and EditTexts
Related
hello guys i'm back again on a question conserning my final project.
i have made a googlemap app with navigation drawer using activity( no fragment). i think you know about that. then rather than using header and menu, i have use a layout where the header should be so that i can make there a listview to display events all of this is clear.
screenshot
MapActivity :
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback {
private static final String TAG = "MapActivity";
DrawerLayout drawerLayout;
LinearLayout drawer_up;
FloatingActionsMenu mainfloating;
FloatingActionButton profile, evennement, historique,reglage,aidesupport;
ImageButton zoomin,zoomout,showtail,zoom_auto,showgeofence,maplayer,drawermenugroit,drawermenugauche;
ProgressDialog progressDialog;
private Dialog mDialog;
private GoogleMap map;
private Timer timer;
private int autoZoomedTimes = 0;// dėl bugo osmdroid library, zoom'inam du kartus ir paskui po refresh'o nebe, nes greičiausiai user'is bus pakeitęs zoom'ą
RelativeLayout nodata_layout;
private HashMap<Integer, Marker> deviceIdMarkers;
private HashMap<String, Device> markerIdDevices;
private HashMap<Integer, Polyline> deviceIdPolyline;
private HashMap<Integer, LatLng> deviceIdLastLatLng;
// private HashMap<Integer, Marker> deviceIdSmallMarkerInfo;
private long lastRefreshTime;
boolean isAutoZoomEnabled = true;
boolean isShowTitlesEnabled;
boolean isShowTailsEnabled = true;
boolean isShowGeofencesEnabled = true;
private String stopTime;
ImageButton map_layer_icon;
private AsyncTask downloadingAsync;
#Bind(R.id.listevent)
ListView listevent;
#Bind(R.id.clearAllEvents)
Button clearAllEvents;
#Bind(R.id.list) ListView list;
#Bind(R.id.nodata_layout) RelativeLayout nodata_layout1;
private boolean isRefreshLoced = false;
ApiInterface.GetGeofencesResult geofencesResult;
ArrayList<PolygonWithName> polygonsWithDetails = new ArrayList<>();
float previousZoomLevel = 0;
Boolean isAllFabsVisible;
RelativeLayout content_layout;
//fin de declaration a garder en tete
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ButterKnife.bind(this);
setContentView(R.layout.activity_map);
//devices elements
deviceIdMarkers = new HashMap<>();
markerIdDevices = new HashMap<>();
deviceIdPolyline = new HashMap<>();
deviceIdLastLatLng = new HashMap<>();
final String api_key = (String) DataSaver.getInstance(MapActivity.this).load("api_key");
final EventsAdapter adapter = new EventsAdapter(this);
listevent.setAdapter(adapter);
//deviceIdSmallMarkerInfo = new HashMap<>();
//delaration des boutons pour le compte de floatingButton, etc...;
drawermenugroit = findViewById(R.id.drawermenudroit);
drawer_up = findViewById(R.id.drawerup);
drawermenugauche = findViewById(R.id.drawermenugauche);
drawerLayout = findViewById(R.id.drawer);
// profile = findViewById(R.id.profile);
mainfloating = findViewById(R.id.mainFloatingBtn);
evennement = findViewById(R.id.evennements);
historique = findViewById(R.id.historiques);
reglage = findViewById(R.id.reglages);
aidesupport = findViewById(R.id.aide_support);
zoomin = findViewById(R.id.zoom_in);
LinearLayout list_event = findViewById(R.id.list_event);
zoomout = findViewById(R.id.zoom_out);
showtail = findViewById(R.id.showtails);
zoom_auto = findViewById(R.id.autozoom);
listevent = (ListView) findViewById(R.id.listevent);
list = (ListView) findViewById(R.id.list);
showgeofence = findViewById(R.id.geofences);
maplayer = findViewById(R.id.map_layer);
map_layer_icon = (ImageButton) findViewById(R.id.map_layer);
//loading_bar = (ProgressBar) findViewById(R.id.loading_progBar);
content_layout = (RelativeLayout) findViewById(R.id.content_layout);
nodata_layout = (RelativeLayout) findViewById(R.id.nodata_layout);
//fin de declaration de boutons
//chargement des données
progressDialog = new ProgressDialog(this);
progressDialog = new ProgressDialog(MapActivity.this);
progressDialog.setMessage("En cours..."); // Setting Message
progressDialog.setTitle("Chargement de la carte"); // Setting Title
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // Progress Dialog Style Spinner
progressDialog.show(); // Display Progress Dialog
progressDialog.setCancelable(false);
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(10000);
} catch (Exception e) {
e.printStackTrace();
}
progressDialog.dismiss();
}
}).start();
// fni de chargement des données
//open drawer and load list data in drawer layout button
drawermenugauche.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openDrawer(drawerLayout);
API.getApiInterface(MapActivity.this).getEvents(api_key, getResources().getString(R.string.lang), 0, new Callback<ApiInterface.GetEventsResult>() {
#Override
public void success(ApiInterface.GetEventsResult result, Response response) {
adapter.setArray(result.items.data);
if(result.items.data.size() != 0)
listevent.setVisibility(View.VISIBLE);
else
nodata_layout1.setVisibility(View.VISIBLE);
listevent.setVisibility(View.GONE);
}
#Override
public void failure(RetrofitError retrofitError) {
Toast.makeText(MapActivity.this, R.string.errorHappened, Toast.LENGTH_SHORT).show();
}
});
}
});
drawer_up.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
closeDrawer(drawerLayout);
}
});
zoomin.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
map.animateCamera(CameraUpdateFactory.zoomIn());
}
});
zoomout.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
map.animateCamera(CameraUpdateFactory.zoomOut());
}
});
zoom_auto.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
isAutoZoomEnabled = !isAutoZoomEnabled;
if (isAutoZoomEnabled)
{
zoom_auto.setImageResource(R.drawable.icon2022);
Toast.makeText(MapActivity.this, "Zoom Auto Activé", Toast.LENGTH_SHORT).show();
} else
{
zoom_auto.setImageResource(R.drawable.disableicon2022);
Toast.makeText(MapActivity.this, "Zoom Auto Désactivé", Toast.LENGTH_SHORT).show();
}
}
});
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
// ouverture et fermeture de drawer
private static void openDrawer(DrawerLayout drawerLayout){
drawerLayout.openDrawer(GravityCompat.START);
}
private static void closeDrawer(DrawerLayout drawerLayout){
if(drawerLayout.isDrawerOpen(GravityCompat.START)){
drawerLayout.closeDrawer(GravityCompat.START);
}
}
//fin ouverture et fermeture drawer
......etc...
see my EventsAdapter code below:
public class EventsAdapter extends AwesomeAdapter<Event> {
public EventsAdapter(Context context) {
super(context);
}
ArrayList<Event> original;
#Override
public void setArray(ArrayList<Event> array) {
super.setArray(array);
if(original == null)
original = array;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null)
convertView = getLayoutInflater().inflate(R.layout.adapter_events, null);
Event item = getItem(position);
TextView device_name = (TextView) convertView.findViewById(R.id.device_name);
device_name.setText(item.device_name);
TextView date = (TextView) convertView.findViewById(R.id.date);
date.setText(item.time);
TextView message = (TextView) convertView.findViewById(R.id.message);
message.setText(item.message);
TextView geofence_name = (TextView) convertView.findViewById(R.id.geofence_name);
geofence_name.setText(item.geofence_name);
return convertView;
}
ItemFilter mFilter = new ItemFilter();
public Filter getFilter() {
return mFilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint)
{
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
final ArrayList<Event> nlist = new ArrayList<>();
for(Event item : original)
{
if(item.fitForFilter(filterString))
nlist.add(item);
}
results.values = nlist;
results.count = nlist.size();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
setArray((ArrayList<Event>) results.values);
notifyDataSetChanged();
}
}
}
then in my adapter_event layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:background="#color/whitesplash"
android:layout_marginBottom="10dp"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/instance"
android:layout_width="16dp"
android:layout_height="22dp"
android:src="#drawable/custom_floating_button" />
<TextView
android:id="#+id/device_nam"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#+id/instance"
android:fontFamily="#font/fjallaoneregular"
android:text="Info Balise"
android:textColor="#color/black"
android:textSize="8dp"
android:textStyle="normal" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_below="#+id/device_nam"
android:outlineAmbientShadowColor="#color/blue" />
<TextView
android:id="#+id/device_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/device_nam"
android:layout_marginStart="16dp"
android:fontFamily="#font/fjallaoneregular"
android:text="device name"
android:textColor="#color/blue"
android:textSize="8dp"
android:textStyle="italic" />
<TextView
android:id="#+id/textspeed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="3dp"
android:layout_toEndOf="#+id/device_nam"
android:fontFamily="#font/fjallaoneregular"
android:text="Vitesse"
android:textColor="#color/black"
android:textSize="8dp"
android:textStyle="italic" />
<TextView
android:id="#+id/speed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textspeed"
android:layout_marginStart="3dp"
android:layout_toEndOf="#+id/device_name"
android:fontFamily="#font/fjallaoneregular"
android:text="speed"
android:textColor="#color/blue"
android:textSize="8dp"
android:textStyle="italic" />
<TextView
android:id="#+id/message1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="3dp"
android:layout_toRightOf="#+id/textspeed"
android:fontFamily="#font/fjallaoneregular"
android:text="message"
android:textColor="#color/black"
android:textSize="8dp"
android:textStyle="normal" />
<TextView
android:id="#+id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textspeed"
android:layout_marginStart="3dp"
android:layout_toEndOf="#+id/speed"
android:fontFamily="#font/fjallaoneregular"
android:text="massage"
android:textColor="#color/blue"
android:textSize="8sp"
android:textStyle="italic" />
<View
android:id="#+id/view2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/device_name" />
<TextView
android:id="#+id/datetext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/device_name"
android:layout_toEndOf="#+id/instance"
android:fontFamily="#font/fjallaoneregular"
android:text="date:"
android:textColor="#color/black"
android:textSize="8dp"
android:textStyle="normal" />
<TextView
android:id="#+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/device_name"
android:layout_marginStart="3dp"
android:layout_toEndOf="#+id/datetext"
android:fontFamily="#font/fjallaoneregular"
android:text="date"
android:textColor="#color/blue"
android:textSize="8sp"
android:textStyle="italic" />
<TextView
android:id="#+id/geofence_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="geofence_name"
android:fontFamily="#font/lobsterregular"
android:layout_below="#+id/date"
android:layout_marginStart="3dp"
android:layout_toRightOf="#+id/instance"
android:textSize="8dp"
android:textColor="#color/blue"/>
</RelativeLayout>
in this adpater_events i have found no mistake. and in the drawer_tracesas i said before( i am not using menu and header in navigationDrawer i would like to use a layout that i called drawer_traces) like below
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/drawerup"
android:orientation="horizontal"
android:background="#color/blue">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/objects"
android:src="#drawable/ic_menu_24"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="16sp"
android:text="#string/objects" />
</LinearLayout>
<TextView
android:id="#+id/Liste_Balises"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/drawerup"
android:fontFamily="#font/fjallaoneregular"
android:gravity="center"
android:text="#string/liste_balises"
android:textColor="#color/blue" />
<LinearLayout
android:id="#+id/list_balises"
android:layout_width="match_parent"
android:layout_height="300dp"
android:orientation="vertical"
android:layout_below="#+id/Liste_Balises"
android:layout_marginTop="10dp"
android:minHeight="?android:attr/listPreferredItemHeight">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:orientation="vertical" />
</LinearLayout>
<TextView
android:id="#+id/list_events"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/list_balises"
android:layout_marginTop="10dp"
android:fontFamily="#font/fjallaoneregular"
android:gravity="center"
android:text="#string/liste_evennemT"
android:textColor="#color/blue" />
<LinearLayout
android:id="#+id/list_event"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_below="#+id/list_events"
android:layout_marginTop="10dp"
android:minHeight="?android:attr/listPreferredItemHeight">
<ListView
android:id="#+id/listevent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:orientation="vertical" />
</LinearLayout>
<RelativeLayout
android:id="#+id/nodata_layout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/list_event"
android:layout_above="#+id/clearAllEvents"
android:background="#ffffff"
android:visibility="gone"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/noEventsData"/>
</RelativeLayout>
<Button
android:id="#+id/clearAllEvents"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/list_event"
android:fontFamily="#font/fjallaoneregular"
android:text="Effacer Evennements"/>
</RelativeLayout>
this layout (drawer_trace) will be displayed in mapActivity as a navigation Drawer. we are ok for that.
and then i have my Events Model:
public class Event
{
public int id, user_id, device_id, position_id, alert_id;
// geofence_id
public String message;
public String address;
public float altitude;
// course
public float latitude, longitude;
// power
public float speed;
public String time;
// deleted
public String device_name, geofence_name;
public boolean fitForFilter(String filterString) {
if(message.toLowerCase().contains(filterString.toLowerCase()))
return true;
if(address.toLowerCase().contains(filterString.toLowerCase()))
return true;
if(time.toLowerCase().contains(filterString.toLowerCase()))
return true;
if(device_name.toLowerCase().contains(filterString.toLowerCase()))
return true;
if(geofence_name.toLowerCase().contains(filterString.toLowerCase()))
return true;
return false;
}
i am using REST API in backend and retrofit.
everything is ok untill i try to eun the app.
it says ERROR MESSAGE:
Process: com.gabontech.gprstest, PID: 14460
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gabontech.gprstest/com.gabontech.gprstest.activities.MapActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3433)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3572)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:140)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:96)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2097)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:264)
at android.app.ActivityThread.main(ActivityThread.java:7663)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:980)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at com.gabontech.gprstest.activities.MapActivity.onCreate(MapActivity.java:139)
at android.app.Activity.performCreate(Activity.java:7805)
at android.app.Activity.performCreate(Activity.java:7794)
i think about the adapter where in EventsAdapter.class line ref:::::
convertView = getLayoutInflater().inflate(R.layout.adapter_events, null);
ihave spent two days there. please if you can help it will give me a hand for my exam. Thank so much guys
I have my project in registration to web service with JSON object in response.
This is the registration class:
public class RegisterReq extends AppCompatActivity {
ProgressDialog pDialogreg;
Button register;
EditText tx_username,tx_password,
tx_nama,tx_alamat,
tx_telepon,tx_email,
tx_no_ktp, tx_confirm_pass;
Intent intent;
int success;
ConnectivityManager conMgr;
private SessionManager session;
private static final String TAG = RegisterReq.class.getSimpleName();
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "massage";
String tag_json_obj = "json_obj_req";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register_req);
pDialogreg = new ProgressDialog(this);
pDialogreg.setCancelable(false);
register = (Button) findViewById(R.id.btn_register);
tx_username = (EditText) findViewById(R.id.username);
tx_password = (EditText)findViewById(R.id.password);
tx_confirm_pass = (EditText) findViewById(R.id.confirm_password);
tx_nama = (EditText) findViewById(R.id.nama);
tx_alamat = (EditText) findViewById(R.id.alamat);
tx_email= (EditText) findViewById(R.id.email);
tx_telepon=(EditText) findViewById(R.id.telepon);
tx_no_ktp = (EditText) findViewById(R.id.no_ktp);
register.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String username = tx_username.getText().toString().trim();
String password = tx_password.getText().toString().trim();
String confirm_password = tx_confirm_pass.getText().toString().trim();
String nama = tx_nama.getText().toString().trim();
String alamat =tx_alamat.getText().toString().trim();
String telepon = tx_telepon.getText().toString().trim();
String email = tx_email.getText().toString().trim();
String no_ktp = tx_no_ktp.getText().toString().trim();
if(password.equals(confirm_password) ){
checkRegister(username, password, nama, alamat, telepon, email, no_ktp );
} else {
Toast.makeText(getApplicationContext(), "Password not Match with Confirm", Toast.LENGTH_SHORT).show();
}
}
});
session = new SessionManager(getApplicationContext());
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(RegisterReq.this,
MainActivity.class);
startActivity(intent);
finish();
}
}
private void checkRegister(final String username,
final String password,
final String nama,
final String alamat,
final String telepon,
final String email,
final String no_ktp
) {
pDialogreg.setMessage("Register ...");
showDialog();
String url ="http://gis.sigjalan.com/web-services-db.php?flag=fAddUser&username="+username+
"&password="+password+
"&nama="+nama+
"&alamat="+alamat+
"&telepon="+telepon+
"&email="+email+
"&no_ktp="+no_ktp;
JsonArrayRequest strReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.e(TAG, "Register Response: " + response.toString());
hideDialog();
String result = response.toString();
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray Jarray = jsonObject.getJSONArray("contacts");
for (int i = 0; i < result.length(); i++) {
JSONObject Jasonobject = Jarray.getJSONObject(i);
}
Toast.makeText(getApplicationContext(),"User successfully registered. Try login now!", Toast.LENGTH_LONG).show();
startActivity( new Intent(RegisterReq.this,MainActivity.class));
} catch (JSONException e){
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
},
//untuk error
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Erorrvoley " + error.getMessage());
Toast.makeText(getApplicationContext(),
"error voley"+error.getMessage(), Toast.LENGTH_LONG).show();
}
});
// Adding request to request queue
AppController.getInstance(this).addToRequestQueue(strReq);
}
private void showDialog() {
if (!pDialogreg.isShowing())
pDialogreg.show();
}
private void hideDialog() {
if (pDialogreg.isShowing())
pDialogreg.dismiss();
}}
This is the activity file of registration form:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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.gun21.gunawan.gispro.RegisterReq">
<LinearLayout android:layout_width="match_parent" android:layout_height="match_parent">
android:orientation="vertical"
<ScrollView android:id="#+id/register_req_form" android:layout_height="wrap_content" android:layout_width="match_parent">
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:orientation="vertical">
<View android:id="#+id/View1" android:layout_width="fill_parent" android:layout_height="1dp" android:layout_gravity="center" android:background="#448AFF" />
<TextView android:id="#+id/TextView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="30dip" android:textColor="#C0392B" android:text="REGISTER BELOW" android:textSize="16dip"
/>
<android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content">
<EditText android:id="#+id/username" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_margin="10dp" android:hint="Username" android:inputType="textEmailAddress" android:singleLine="true"
/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content">
<EditText android:id="#+id/password" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_margin="10dp" android:hint="Password" android:password="true" android:singleLine="true" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content">
<EditText android:id="#+id/confirm_password" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_margin="10dp" android:hint="Comfirmation Password" android:password="true" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content">
<EditText android:id="#+id/nama" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:hint="Nama" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content">
<EditText android:id="#+id/alamat" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:hint="Alamat" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content">
<EditText android:id="#+id/telepon" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:hint="Telepon" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content">
<EditText android:id="#+id/email" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:hint="Email" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content">
<EditText android:id="#+id/no_ktp" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:hint="No KTP" />
</android.support.design.widget.TextInputLayout>
<Button android:id="#+id/btn_register" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:layout_gravity="center" android:layout_marginBottom="15dp" android:background="#2980B9" android:textColor="#fff"
android:text="Register" android:textStyle="bold" android:paddingLeft="#dimen/activity_horizontal_margin" android:paddingRight="#dimen/activity_horizontal_margin" />
</LinearLayout>
</ScrollView>
</LinearLayout>
</android.support.constraint.ConstraintLayout>
This is the response:
{
"id_user_pemilik_kos": 73
}
and this is the error:
05 - 26 03: 04: 49.513 30080 - 30080 / com.gun21.gunawan.gispro E / RegisterReq: Erorrvoley org.json.JSONException: Value {
"id_user_pemilik_kos": 74
} of type org.json.JSONObject cannot be converted to JSONArray
I don't know what is the problem so, what can be done to solve this problem ?
It looks like the service that lives at the requested URL is returning a single JSON object, and not an array of JSON objects.
Try changing your strReq from a JsonArrayRequest to a JsonObjectRequest. That means the onResponse function will accept a JSONObject parameter instead of a JSONArray.
JsonObjectRequest strReq = new JsonObjectRequest(url,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// ...
// Note: you will likely not need this conversion to a JSONObject anymore
// JSONObject jsonObject = new JSONObject(result); <-- Not needed now
}
}
I believe this page will help explain the difference between JsonArrayRequest and JsonObjectRequest.
Change the code like this:
JsonObjectRequest strReq = new JsonObjectRequest(url,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}
You have given that you will get an JsonArray from response. In onResponse() method's body you have used JsonObject. You have mixed up.
i have fragment for send data to server, but my edit Text always null, no error in application only cannot get the value from edit text
this is my XML
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
<Button
android:text="Submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/submit_laporan"
android:layout_below="#+id/desc_masalah"
android:layout_centerHorizontal="true"
android:layout_marginTop="36dp" />
<TextView
android:text="Judul"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView5"
android:textSize="18sp"
android:layout_alignParentTop="true"
android:layout_marginTop="14dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:paddingLeft="10dp" />
<TextView
android:text="Deskripsi Masalah"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="19dp"
android:id="#+id/textView4"
android:textSize="18sp"
android:layout_below="#+id/judul_masalah"
android:layout_alignLeft="#+id/textView5"
android:layout_alignStart="#+id/textView5"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:paddingLeft="10dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:ems="10"
android:layout_marginTop="13dp"
android:id="#+id/desc_masalah"
android:layout_below="#+id/textView4"
android:layout_alignLeft="#+id/textView4"
android:layout_alignStart="#+id/textView4"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:paddingLeft="10dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/judul_masalah"
android:layout_marginTop="13dp"
android:layout_below="#+id/textView5"
android:layout_alignLeft="#+id/textView5"
android:layout_alignStart="#+id/textView5"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:paddingLeft="10dp" />
</RelativeLayout>
and this is my JAVA
public class Report extends Fragment{
EditText judul_masalah, desc_masalah;
Button submit_laporan;
//public Report(){}
//RelativeLayout view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View V = inflater.inflate(R.layout.laporan, container, false);
getActivity().setTitle("Pelaporan");
/*submit_laporan.setOnClickListener(new View.OnClickListener(){
String newJudul = judul_masalah.getText().toString();
String newDeskripsi = desc_masalah.getText().toString();
#Override
public void onClick(View v){
Toast.makeText(getActivity(), newJudul,
Toast.LENGTH_LONG).show();
new sendData().execute(newJudul,newDeskripsi);
}
});*/
return V;
}
public void onViewCreated(View V, Bundle savedInstanceState){
judul_masalah = (EditText) V.findViewById(R.id.judul_masalah);
desc_masalah = (EditText) V.findViewById(R.id.desc_masalah);
submit_laporan = (Button) V.findViewById(R.id.submit_laporan);
submit_laporan.setOnClickListener(new View.OnClickListener(){
String newJudul = judul_masalah.getText().toString();
String newDeskripsi = desc_masalah.getText().toString();
#Override
public void onClick(View v){
Toast.makeText(getActivity(), newJudul,
Toast.LENGTH_LONG).show();
//new sendData().execute(newJudul,newDeskripsi);
}
});
}
public class sendData extends AsyncTask<String, String, JSONObject>{
HttpURLConnection conn;
URL url = null;
JSONParser jsonParser = new JSONParser();
private static final String TAG_INFO = "info";
private static final String LAPORAN_URL = "URL";
#Override
protected JSONObject doInBackground(String... args) {
try {
HashMap<String, String> params = new HashMap<>();
params.put("judul", args[0]);
params.put("deskripsi", args[1]);
Log.d("request", "starting");
JSONObject json = jsonParser.makeHttpRequest(
LAPORAN_URL, "POST", params);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(JSONObject json) {
String info = "";
if (json != null) {
//Toast.makeText(LoginActivity.this, json.toString(),
//Toast.LENGTH_LONG).show();
try {
info = json.getString(TAG_INFO);
} catch (JSONException e) {
e.printStackTrace();
}
}
if(info.equals("Success")) {
Toast.makeText(getActivity(), "Data Berhasil Disimpan",
Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getActivity(), "Data Gagal Disimpan",
Toast.LENGTH_LONG).show();
}
}
}
}
anyone can help me whats wrong with my code
You have to place your getText() inside the methode onClick(). Now it's outside and doesn't work.
The line :
"String newJudul = judul_masalah.getText().toString();"
after the line:
"public void onClick(View v){"
i cannot save selected radio buttons and spinner into mysql database? why is this?but for editText, it saves to my database.please help!
here is my submitData.php
<html>
<body>
<form action="submitData" method = "post">
Gender <input type = "radio" name="gender" value ="<?php echo $row['Gender']?>">
<input type = "radio" name="gender" value ="<?php echo $row['Gender']?>"
</form>
</body>
</html>
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$Name = $_POST['Name'];
$Age = $_POST['Age'];
$Gender=$_POST['Gender'];
$Email = $_POST['Email'];
$Phone = $_POST['Phone'];
$IncidentType = $_POST['IncidentType'];
$Description = $_POST['Description'];
require_once('dbConnect.php');
$sql = "INSERT INTO user (Name,Age,Gender,Email,Phone,IncidentType,Description) VALUES ('$Name','$Age','$Gender','$Email','$Phone','$IncidentType','$Description')";
if(mysqli_query($con,$sql)){
echo "Successfully sent";
}else{
echo "Could not send";
}
}else{
echo 'error';
}
?>
here is my FormActivity.java:
public class FormActivity extends Activity implements View.OnClickListener, AdapterView.OnItemSelectedListener {
private static final String REGISTER_URL = "http://khaty-ismail0.rhcloud.com/phptutorial/submitData.php";
private static final String SPINNER_URL = "http://khaty-ismail0.rhcloud.com/phptutorial/spinner_data.php";
public static final String KEY_NAME= "Name";
public static final String KEY_AGE = "Age";
public static final String KEY_EMAIL = "Email";
public static final String KEY_PHONE = "Phone";
public static final String KEY_DESCRIPTION = "Description";
public static final String KEY_TICKET = "ticket_id";
public static final String KEY_SOLUTION = "solution";
public static final String JSON_ARRAY = "result";
private EditText name_eT;
private EditText age_eT;
private EditText email_eT;
private EditText phone_eT;
private EditText descr_eT;
private Button subm_btn;
private Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_form);
name_eT = (EditText) findViewById(R.id.name_eT);
age_eT = (EditText) findViewById(R.id.age_eT);
email_eT= (EditText) findViewById(R.id.email_eT);
phone_eT= (EditText) findViewById(R.id.phone_eT);
descr_eT= (EditText) findViewById(R.id.descr_eT);
subm_btn = (Button) findViewById(R.id.subm_btn);
subm_btn.setOnClickListener(this);
spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getBaseContext(), spinner.getSelectedItem().toString(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
private void registerUser(){
final String Name = name_eT.getText().toString().trim();
final String Age = age_eT.getText().toString().trim();
final String Email = email_eT.getText().toString().trim();
final String Phone = phone_eT.getText().toString().trim();
final String Description = descr_eT.getText().toString().trim();
if(TextUtils.isEmpty(Name)) {
name_eT.setError("Please enter your name");
return;
}else if(TextUtils.isEmpty(Age)) {
age_eT.setError("Please enter your age");
return;
}else if(TextUtils.isEmpty(Phone)) {
phone_eT.setError("Please enter your phone");
return;
}else if(TextUtils.isEmpty(Email)) {
email_eT.setError("Please enter your email");
return;
}else if(TextUtils.isEmpty(Description)) {
descr_eT.setError("Please enter your issue");
return;
}
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(FormActivity.this,response,Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(FormActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(KEY_NAME,Name);
params.put(KEY_AGE,Age);
params.put(KEY_EMAIL, Email);
params.put(KEY_PHONE, Phone);
params.put(KEY_DESCRIPTION, Description);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
public void onCheckboxClicked(View V) {
boolean checked = ((RadioButton) V).isChecked();
switch (V.getId()) {
case R.id.male_rb:
if (checked)
break;
case R.id.female_rb:
if (checked)
break;
}
}
#Override
public void onClick(View v) {
if(v == subm_btn){
registerUser();
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public void submitData(View view) {
Intent getResponse = new Intent(this,SubmitData.class);
final int result = 1;
startActivityForResult(getResponse, result);
}
}
here is my activity_form.java:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:background="#color/buttonFont"
tools:context="com.example.khadijah.brucertv2.FormActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="#string/User_info"
android:id="#+id/userInfo"
android:textSize="30sp"
android:textColor="#color/colorFont"
android:textStyle="bold"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"/>
<TextView
android:layout_width="70dp"
android:layout_height="wrap_content"
android:text="Name:"
android:id="#+id/name_tV"
android:textColor="#color/colorFont"
android:layout_marginTop="24dp"
android:layout_below="#+id/userInfo"
android:layout_alignLeft="#+id/userInfo"
android:layout_alignStart="#+id/userInfo" />
<TextView
android:layout_width="70dp"
android:layout_height="wrap_content"
android:text="Age:"
android:id="#+id/age_tV"
android:textColor="#color/colorFont"
android:layout_alignBottom="#+id/age_eT"
android:layout_alignLeft="#+id/name_tV"
android:layout_alignStart="#+id/name_tV" />
<TextView
android:layout_width="70dp"
android:layout_height="wrap_content"
android:text="Gender"
android:id="#+id/gender_tV"
android:textColor="#color/colorFont"
android:layout_below="#+id/age_tV"
android:layout_alignLeft="#+id/age_tV"
android:layout_alignStart="#+id/age_tV"
android:layout_marginTop="24dp" />
<TextView
android:layout_width="70dp"
android:layout_height="wrap_content"
android:text="Email:"
android:id="#+id/email_tV"
android:textColor="#color/colorFont"
android:layout_alignBottom="#+id/email_eT"
android:layout_alignLeft="#+id/name_tV"
android:layout_alignStart="#+id/name_tV" />
<TextView
android:layout_width="70dp"
android:layout_height="wrap_content"
android:text="Phone"
android:id="#+id/phone_tV"
android:textColor="#color/colorFont"
android:layout_alignBottom="#+id/phone_eT"
android:layout_alignLeft="#+id/gender_tV"
android:layout_alignStart="#+id/gender_tV" />
<EditText
android:layout_width="200dp"
android:layout_height="30dp"
android:layout_marginBottom="5dp"
android:inputType="textPersonName"
android:hint="#string/hint_required"
android:textColorHint="#color/buttonFont"
android:background="#drawable/border_style"
android:ems="10"
android:id="#+id/name_eT"
android:textColor="#color/inputFont"
android:layout_alignBottom="#+id/name_tV"
android:layout_alignRight="#+id/userInfo"
android:layout_alignEnd="#+id/userInfo" />
<EditText
android:layout_width="200dp"
android:layout_height="30dp"
android:inputType="number"
android:ems="10"
android:hint="#string/hint_required"
android:textColorHint="#color/buttonFont"
android:background="#drawable/border_style"
android:id="#+id/age_eT"
android:textColor="#color/inputFont"
android:layout_below="#+id/name_tV"
android:layout_alignRight="#+id/userInfo"
android:layout_alignEnd="#+id/userInfo" />
<EditText
android:layout_width="200dp"
android:layout_height="30dp"
android:inputType="textEmailAddress"
android:ems="10"
android:id="#+id/email_eT"
android:hint="#string/hint_required"
android:textColorHint="#color/buttonFont"
android:textColor="#color/inputFont"
android:background="#drawable/border_style"
android:layout_below="#+id/phone_eT"
android:layout_alignLeft="#+id/age_eT"
android:layout_alignStart="#+id/age_eT" />
<EditText
android:layout_width="200dp"
android:layout_height="30dp"
android:inputType="phone"
android:ems="10"
android:id="#+id/phone_eT"
android:layout_marginBottom="5dp"
android:textColor="#color/inputFont"
android:hint="#string/hint_required"
android:textColorHint="#color/buttonFont"
android:background="#drawable/border_style"
android:layout_below="#+id/gender_tV"
android:layout_alignLeft="#+id/email_eT"
android:layout_alignStart="#+id/email_eT" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="#string/incident_info"
android:id="#+id/incidentInfo"
android:textColor="#color/colorFont"
android:textStyle="bold"
android:textSize="30sp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/spinner"
android:prompt="#array/incident_type"
android:entries="#array/incident_type"
android:layout_below="#+id/incidentInfo"
android:layout_alignLeft="#+id/phone_eT"
android:layout_alignStart="#+id/phone_eT"
android:layout_alignRight="#+id/phone_eT"
android:layout_alignEnd="#+id/phone_eT"
android:spinnerMode="dropdown" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="#string/incident_type_DD"
android:textColor="#color/colorFont"
android:id="#+id/incident_DD"
android:layout_below="#+id/incidentInfo"
android:layout_toLeftOf="#+id/spinner"
android:layout_toStartOf="#+id/spinner" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="#string/description"
android:id="#+id/description_tV"
android:textColor="#color/colorFont"
android:layout_below="#+id/spinner"
android:layout_alignLeft="#+id/phone_tV"
android:layout_alignStart="#+id/phone_tV" />
<EditText
android:layout_width="300dp"
android:layout_height="80dp"
android:inputType="textMultiLine"
android:ems="10"
android:id="#+id/descr_eT"
android:hint="#string/descr_hint"
android:textColorHint="#color/buttonFont"
android:gravity="top"
android:background="#drawable/border_style"
android:textColor="#color/inputFont"
android:layout_below="#+id/description_tV"
android:layout_alignLeft="#+id/description_tV"
android:layout_alignStart="#+id/description_tV" />
<Button
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_margin="5dp"
android:text="SUBMIT"
android:onClick="submitData"
android:textStyle="bold"
android:textSize="35sp"
android:id="#+id/subm_btn"
android:background="#drawable/custom_btn"
android:textColor="#color/buttonFont"
android:layout_alignParentBottom="true"/>
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_alignLeft="#+id/phone_eT"
android:layout_alignStart="#+id/phone_eT"
android:layout_below="#+id/age_eT"
android:layout_alignRight="#+id/descr_eT"
android:layout_alignEnd="#+id/descr_eT"
android:layout_above="#+id/phone_eT"
android:weightSum="1"
android:id="#+id/radioGroup">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="false"
android:text="Male"
android:id="#+id/male_rb"
android:onClick="onCheckboxClicked"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
android:checked="false"
android:id="#+id/female_rb"
android:onClick="onCheckboxClicked"/>
</RadioGroup>
</RelativeLayout>
here is my arrays.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="incident_type">
<item>Fraud</item>
<item>Malicious Code</item>
<item>Spam</item>
<item>Intrusion</item>
<item>Not Sure</item>
</string-array>
</resources>
the form name is case sensitive.
use $_POST['gender'];
another thing is. where is your definition of $row? looks like it may be empty so you will not post any data.
enable error_reporting and display_errors while development help you to find such kind of errors much faster
another thing very important dont use mysql_* functions they are insecure and deprecated. have a look ad PDO instead
also use prepared statements and escape userinput.
I have a DB in mysql, I want to show all the data in the DB as a list of chkbox with the data from the DB . and after selection of few checkbox i can fire query to DB for certain data about the selected ones. I have tried using listView below is my JAVA file and xml
here is JAVA file
public class BdaySelect extends Activity {
private String jsonResult;
private String url = "http://10.0.2.2/markit/login.php";
private ListView listView;
private TextView textv1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bday_select);
listView = (ListView) findViewById(R.id.listView1);
textv1=(TextView)findViewById(R.id.textView1);
accessWebService();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrwaer();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void ListDrwaer() {
List<Map<String, String>> employeeList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("emp_info");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.getString("emp_name");
String number = jsonChildNode.getString("emp_no");
//String chkBoxNo = Integer.toString(i);
//String chkBoxName = "chk"+chkBoxNo;
//CheckBox chkBoxName = new CheckBox(this);
String outPut = name + "-" + number;
employeeList.add(createEmployee("employees", outPut));
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList,
android.R.layout.simple_list_item_1,
new String[] { "employees" }, new int[] { android.R.id.text1 });
listView.setAdapter(simpleAdapter);
}
private HashMap<String, String> createEmployee(String name, String number) {
HashMap<String, String> employeeNameNo = new HashMap<String, String>();
employeeNameNo.put(name, number);
return employeeNameNo;
}
}
XML file
<?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" >
<TableRow
android:id="#+id/tableRow2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#29001F"
android:gravity="center" >
<ImageView
android:id="#+id/imageView2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="#drawable/bck" />
<Space
android:layout_width="100dp"
android:layout_height="30dp"
android:layout_weight="2" />
<ImageButton
android:id="#+id/imageButton1"
android:paddingRight="10dp"
android:background="#29001F"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/setting2" />
</TableRow>
<TableRow
android:background="#29001F"
android:id="#+id/tableRow1"
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center" >
<TextView
android:id="#+id/textView1"
android:layout_width="0dp"
android:gravity="center"
android:textColor="#FFFFFF"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="SELECT"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView2"
android:layout_width="0dp"
android:gravity="center"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#94808F"
android:text="DISCOUNT"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView3"
android:layout_width="0dp"
android:gravity="center"
android:layout_height="wrap_content"
android:textColor="#94808F"
android:layout_weight="1"
android:text="SEND"
android:textAppearance="?android:attr/textAppearanceMedium" />
</TableRow>
<Space
android:layout_width="match_parent"
android:layout_height="20dp" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
<TableRow
android:id="#+id/tableRow6"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="102dp"
android:gravity="right"
android:paddingRight="30dp" >
<Button
android:id="#+id/butBdaySelectNext"
android:layout_width="80dp"
android:layout_height="35dp"
android:layout_gravity="center"
android:background="#drawable/arrownext"
android:paddingRight="15dp"
android:text="Next"
android:textColor="#FFFFFF" />
</TableRow>
</LinearLayout>
The basic concept to create a custom list view in android starts with a custom view .xml that will correspond to the layout of how each individual item will look like. For example if you want each item to have a textview for the name and a checkbox your custom layout will only contain a linear (horizontal) layout with a textview and a check box in. After that on your activity you'll need to create a class that extends Base Adapter. The main roll of this class is to get the data you want (from an array for example) and inflate that info to the layout that you created. I found this tutorial that may help you:
http://androidexample.com/How_To_Create_A_Custom_Listview_-_Android_Example/index.php?view=article_discription&aid=67&aaid=92