Get Value from editText in Fragment to Send With Asynctask - java

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){"

Related

recyclerview no showing data of firebase

I try to show data of firebase on a
recycler View but no work please help me what can to be the problem?
my code is down, I can to see space result on my view but not see data
/**
* Create a new RecyclerView adapter that listens to a Firestore Query. See {#link
* FirestoreRecyclerOptions} for configuration options.
*
* #param options
*/
public ClienteAdapter(#NonNull FirestoreRecyclerOptions<cliente> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull ViewHolder viewHolder, int position, #NonNull cliente cli) {
viewHolder.name.setText(cli.getName());
viewHolder.address.setText(cli.getAddress());
viewHolder.phone.setText(cli.getPhone());
viewHolder.product.setText(cli.getProduct());
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_cliente_single, parent, false);
return new ViewHolder (v);
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView name, address, phone, product;
public ViewHolder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.nombre);
address = itemView.findViewById(R.id.direccion);
phone = itemView.findViewById(R.id.telefono);
product = itemView.findViewById(R.id.producto);
}
}
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/nombre"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Nombre" />
<TextView
android:id="#+id/direccion"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Direccion" />
<TextView
android:id="#+id/telefono"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Telefono" />
<TextView
android:id="#+id/producto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Producto" />
</LinearLayout>
here more code class
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<Button
android:id="#+id/btn_inv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Inventario" />
<Button
android:id="#+id/btn_compras"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Compras" />
<Button
android:id="#+id/btn_sorteos"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sorteos" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerViewSingle"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
here more code class
Button btn_inv;
RecyclerView mRecycler;
ClienteAdapter mAdapter;
FirebaseFirestore mFirestore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFirestore = FirebaseFirestore.getInstance();
mRecycler = findViewById(R.id.recyclerViewSingle);
mRecycler.setLayoutManager(new LinearLayoutManager(this));
Query query = mFirestore.collection("cliente");
FirestoreRecyclerOptions<cliente> firestoreRecyclerOptions =
new FirestoreRecyclerOptions.Builder<cliente>().setQuery(query, cliente.class).build();
mAdapter = new ClienteAdapter(firestoreRecyclerOptions);
mAdapter.notifyDataSetChanged();
mRecycler.setAdapter(mAdapter);
btn_inv = findViewById(R.id.btn_inv);
btn_inv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, inventario.class)); }
});
}
#Override
protected void onStart() {
super.onStart();
mAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
mAdapter.stopListening();
}
layout inventario code here
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<EditText
android:id="#+id/nombre"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="nombre"
android:inputType="textPersonName" />
<EditText
android:id="#+id/direccion"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="direccion"
android:inputType="textPersonName" />
<EditText
android:id="#+id/telefono"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="telefono"
android:inputType="textPersonName" />
<EditText
android:id="#+id/producto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="producto"
android:inputType="textPersonName" />
<Space
android:layout_width="match_parent"
android:layout_height="15dp" />
<Button
android:id="#+id/btn_act"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Actualizar" />
<Button
android:id="#+id/btn_guar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Guardar" />
<Button
android:id="#+id/btn_eli"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Eliminar" />
<Button
android:id="#+id/btn_bus"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Buscar" />
<Button
android:id="#+id/btn_todo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Ver Todos" />
</LinearLayout>
the class inventario code here
Button btn_act, btn_guar, btn_eli, btn_bus, btn_todo;
EditText nombre, direccion, telefono, producto;
private
more code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inventario);
this.setTitle("Zona Inventario");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mfirestore = FirebaseFirestore.getInstance();
nombre = findViewById(R.id.nombre);
direccion = findViewById(R.id.direccion);
telefono = findViewById(R.id.telefono);
producto = findViewById(R.id.producto);
btn_act = findViewById(R.id.btn_act);
btn_guar = findViewById(R.id.btn_guar);
btn_eli = findViewById(R.id.btn_eli);
btn_bus = findViewById(R.id.btn_bus);
btn_todo = findViewById(R.id.btn_todo);
btn_guar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String namecli = nombre.getText().toString().trim();
String dircli = direccion.getText().toString().trim();
String telcli = telefono.getText().toString().trim();
String procli = producto.getText().toString().trim();
if (namecli.isEmpty() && dircli.isEmpty() && telcli.isEmpty() && procli.isEmpty()) {
Toast.makeText(getApplicationContext(), "Ingresar Los Datos", Toast.LENGTH_SHORT).show();
} else {
postDatos(namecli, dircli, telcli, procli);
}
}
});
}
private void postDatos(String namecli, String dircli, String telcli, String procli) {
Map<String, Object> map = new HashMap<>();
map.put("nombre", namecli);
map.put("direccion", dircli);
map.put("telefono", telcli);
map.put("producto", procli);
mfirestore.collection("cliente").add(map).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText(inventario.this, "Creado Exitosamente!", Toast.LENGTH_SHORT).show();
finish();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(inventario.this, "Error al Ingresar", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return false;
}
please help me, what the problem on my program?

Set Text not showing from a function inside a fragment

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

Erorrvoley org.json.JSONException: Value of type org.json.JSONObject cannot be converted to JSONArray

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.

Android ListView displaying one item per page

I have a listview that uses an adapter who receives a string array as an argument. When I look at the listview it displays 1 item then it shows a lot of blank space behind it that is followed by the next item if I scroll down. What could be the problem?
class CustomAdapter extends ArrayAdapter<String> {
CustomAdapter(Context context, String[] camere) {
super(context, R.layout.custom_row, camere);
}
boolean parola = true;
boolean intra = true;
String player_id, room_id;
String siteul = "some_site";
String site;
HashMap<String, String> hash;
static class ViewHolder {
TextView camera;
TextView players;
TextView max_players;
ImageView privata;
Button Buton;
String room_id, nume;
}
ViewHolder ceva;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
String variabile[] = getItem(position).split("\\s+");
if(convertView == null)
{
LayoutInflater linflater = LayoutInflater.from(getContext());
convertView = linflater.inflate(R.layout.custom_row, parent, false);
holder = new ViewHolder();
holder.camera = (TextView) convertView.findViewById(R.id.Nume);
holder.players = (TextView) convertView.findViewById(R.id.players);
holder.max_players = (TextView) convertView.findViewById(R.id.max_players);
holder.privata = (ImageView) convertView.findViewById(R.id.privata);
holder.Buton = (Button) convertView.findViewById(R.id.Buton);
holder.camera.setText(variabile[0]);
if (!variabile[1].equals("true")) {
parola = false;
holder.privata.setVisibility(View.INVISIBLE);
}
holder.players.setText(variabile[2]);
holder.max_players.setText(variabile[3]);
holder.room_id = variabile[4];
holder.nume = variabile[5];
holder.Buton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int playeri = Integer.parseInt(holder.players.getText().toString());
int maximi = Integer.parseInt(holder.max_players.getText().toString());
if(playeri < maximi)
{
hash = new HashMap<String, String>();
hash.put("name", holder.nume);
hash.put("room", holder.room_id);
if (intra) {
holder.Buton.setText("Iesi");
site = siteul + "/join";
intra = false;
} else {
holder.Buton.setText("Intra");
site = siteul + "/leave";
intra = true;
}
new ATask((ViewHolder) v.getTag()).execute(site);
}
}
});
convertView.setTag(holder);
holder.Buton.setTag(holder);
}
else
holder = (ViewHolder) convertView.getTag();
return convertView;
}
public void CheckStart()
{
site = siteul + "/checkstart";
hash = new HashMap<String, String>();
hash.put("room", room_id);
new ATask(ceva).execute(site);
}
public void CheckPlayers()
{
site = siteul + "/checkplayers";
hash = new HashMap<String, String>();
hash.put("room", room_id);
new ATask(ceva).execute(site);
}
public void openGame(String litera)
{
Intent incercare = new Intent(getContext(), Game.class);
incercare.putExtra("nume", player_id);
incercare.putExtra("room", room_id);
incercare.putExtra("litera", litera);
incercare.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getContext().startActivity(incercare);
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
public class ATask extends AsyncTask<String, Void, String> {
String rez = "";
ViewHolder myHolder;
public ATask(ViewHolder view) {
myHolder = view;
ceva = myHolder;
room_id = myHolder.room_id;
}
#Override
protected String doInBackground(String... urls) {
//try {
try {
Log.e("rasp", site);
URL obj = new URL(site);
try {
Log.e("rasp", obj.toString());
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
//con.setRequestProperty("User-Agent", USER_AGENT);
// For POST only - START
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(getPostDataString(hash).getBytes());
os.flush();
os.close();
// For POST only - END
int responseCode = con.getResponseCode();
Log.e("rasp", "response code-ul e " + Integer.toString(responseCode));
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
rez = response.toString();
}
else {
Log.e("rasp", "POST request not worked");
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
Log.e("naspa", "E corupt!");
}
//} catch (Exception e) {
// Log.e("rasp", "aia e");
//}
return rez;
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
if (rez.charAt(0) == 'Y')
openGame(rez.substring(2));
else if (rez.charAt(0) == 'V' && !intra)
{
TextView players_mare = myHolder.players;
players_mare.setText(rez.substring(2));
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Do something after 1s = 1000ms
CheckStart();
}
}, 1000);
}
else if(rez.charAt(0) == 'G')
CheckPlayers();
else if(rez.charAt(0) == 'Z')
{
TextView players_mare = myHolder.players;
players_mare.setText(rez.substring(2));
}
else if (rez.charAt(0) == 'D')
{
player_id = rez.substring(2);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Do something after 1s = 1000ms
CheckStart();
}
}, 400);
}
}
}
}
Here is the xml of "custom_row.xml":
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/background_joc">
<ScrollView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginTop="5dp"
android:id="#+id/scrollView">
<LinearLayout
android:background="#color/grey"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_marginTop="10dp"
android:layout_marginLeft="7dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Nume camera"
android:id="#+id/Nume"
android:textSize="25dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Runde:"
android:layout_marginTop="-7dp"
android:layout_marginLeft="3dp"
android:id="#+id/textView15" />
<TextView
android:layout_marginTop="15dp"
android:layout_marginLeft="-30dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="5"
android:id="#+id/runde"
android:textSize="25dp" />
<ImageView
android:layout_marginTop="18dp"
android:layout_marginLeft="20dp"
android:background="#drawable/buton_lock"
android:layout_width="15dp"
android:layout_height="20dp"
android:id="#+id/privata" />
<TextView
android:layout_marginTop="10dp"
android:layout_marginLeft="7dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="0"
android:id="#+id/players"
android:textSize="30dp" />
<TextView
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="? android:attr/textAppearanceMedium"
android:text="/"
android:id="#+id/nu_trebuia_sa_aiba_id"
android:textSize="30dp" />
<TextView
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="5"
android:id="#+id/max_players"
android:textSize="30dp" />
<Button
android:layout_marginTop="10dp"
android:layout_width="90dp"
android:layout_height="40dp"
android:text="Intra"
android:id="#+id/Buton"
android:layout_marginLeft="5dp" />
<TextView
android:layout_marginLeft="50dp"
android:layout_marginTop="50dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text=""
android:id="#+id/e_sa_pacaleasca_match_parentu_de_la_linear_layout"
/>
</LinearLayout>
</ScrollView>
In your custom_row.xml :
change the layout_height of the RelativeLayout, ScrollView and the LinearLayout from fill_parent to wrap_content.
From the R.layout.custom_row we can see that you make the root view(RelativeLayout) fill parent and make the height of ScrollView match_parent. So the Scrollview occupy the full screen. The blank space belongs to scrollview. I think you can remove the scrollview and make the root view(RelativeLayout) wrap content.
Try codes below:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/background_joc">
<ScrollView
android:id="#+id/scrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/grey"
android:orientation="horizontal">
<TextView
android:id="#+id/Nume"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="7dp"
android:layout_marginTop="10dp"
android:text="Nume camera"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="25dp"/>
<TextView
android:id="#+id/textView15"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="3dp"
android:layout_marginTop="-7dp"
android:text="Runde:"
android:textAppearance="?android:attr/textAppearanceSmall"/>
<TextView
android:id="#+id/runde"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="-30dp"
android:layout_marginTop="15dp"
android:text="5"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textSize="25dp"/>
<ImageView
android:id="#+id/privata"
android:layout_width="15dp"
android:layout_height="20dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="18dp"
android:background="#drawable/buton_lock"/>
<TextView
android:id="#+id/players"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="7dp"
android:layout_marginTop="10dp"
android:text="0"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="30dp"/>
<TextView
android:id="#+id/nu_trebuia_sa_aiba_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="/"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="30dp"/>
<TextView
android:id="#+id/max_players"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="5"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="30dp"/>
<Button
android:id="#+id/Buton"
android:layout_width="90dp"
android:layout_height="40dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:text="Intra"/>
<TextView
android:id="#+id/e_sa_pacaleasca_match_parentu_de_la_linear_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginTop="50dp"
android:text=""
android:textAppearance="?android:attr/textAppearanceSmall" />
</LinearLayout>
</ScrollView>
</RelativeLayout>

how to save spinner data and selected radio button saved to mysql database?

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.

Categories

Resources