How to fix org.json.JSONException: on Volley? - java

I am developing Login on android via connection with php (web).
Code
package com.example.salmakhalil.myapplication;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class LoginActivity extends AppCompatActivity {
private EditText email,password;
private Button btn_login;
private TextView link_regist;
private ProgressBar loading;
private static String URL_LOGIN="http://192.168.8.101/android_register_login/login.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loading=findViewById(R.id.loading);
email=findViewById(R.id.email);
password=findViewById(R.id.password);
btn_login=findViewById(R.id.btn_login);
link_regist=findViewById(R.id.link_regist);
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mEmail=email.getText().toString().trim();
String mPass=password.getText().toString().trim();
if (!mEmail.isEmpty() || !mPass.isEmpty()){
Login(mEmail,mPass);
}
else {
email.setError("Please insert email");
password.setError("Please insert Password");
}
}
});
link_regist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
}
});
}
private void Login(String email, String password){
loading.setVisibility(View.VISIBLE);
btn_login.setVisibility(View.GONE);
//I think here facing a problem
StringRequest stringRequest=new StringRequest(Request.Method.POST, URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject=new JSONObject(response);
String success = jsonObject.getString("success");
JSONArray jsonArray=jsonObject.getJSONArray("login");
if (success.equals("1")) {
for (int i=0; i<jsonArray.length();i++){
JSONObject object = jsonArray.getJSONObject(i);
String name = object.getString("name").trim();
String email=object.getString( "email").trim();
Toast.makeText(LoginActivity.this,
"Success Login. \nYour Name : "
+name+"\nYour Email : "
+email, Toast.LENGTH_SHORT)
.show();
loading.setVisibility(View.GONE);
}
}
} catch (JSONException e) {
e.printStackTrace();
loading.setVisibility(View.GONE);
btn_login.setVisibility(View.VISIBLE);
Toast.makeText(LoginActivity.this, "Error!!! " +e.toString(),
Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this, "Error!! " +error.toString(),
Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("email", email);
params.put("password", password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
When I click on the login Button, its showing thee error
org.json.JSONException: No value for success.
I'm all the day trying to fix it. I have read other posts on Stack, no one helped me. I hope you can help me. Thanks.

Apparently the jsonObject your receive in onResponse() does not have a value for entry "success"
You should use the method jsonObject.optString("success"); instead of jsonObject.getString("success");
optString("success") returns the empty string ("") if the key "success" doesn't exist. getString("success") on the other hand throws a JSONException.

Can you share the response that is supposed to get. I think the response doesn't contain any field name "success". Query on postman to get response otherwise talk to your back end developer.

Related

Issue Sending data to mysql in android studio

I am currently building an app for my university project and I am well and truly stuck. I am currently trying to send data from my apps sign up page to my Mysql database, I have gotten as far as being able to connect due to error logs showing that a connection was successful but no data is being sent to the database?
I have tried multiple ways of sending the data through php but it doesn't seem to make any difference. I was hoping maybe someone could point out my mistake and help me get past this hurdle I have been stuck on for so long.
Signup.java
package com.example.projectv1;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SignUp extends AppCompatActivity {
ImageView nxtPage;
EditText Fname;
EditText Lname;
EditText Email;
EditText Password;
EditText RePassword;
private String sendURL = "https://tg322.brighton.domains/AppPHP/get_data.php";
private RequestQueue requestQueue;
private static final String TAG = SignUp.class.getSimpleName();
int success;
private String TAG_SUCCESS = "Success";
private String TAG_MESSAGE = "Message";
private String tag_json_obj = "json_obj_req";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
nxtPage = (ImageView) findViewById(R.id.NextPage);
Fname = (EditText) findViewById(R.id.editTextFName);
Lname = (EditText) findViewById(R.id.editTextLName);
Email = (EditText) findViewById(R.id.editTextEmail);
Password = (EditText) findViewById(R.id.editTextPassword);
RePassword = (EditText) findViewById(R.id.editTextRePassword);
requestQueue = Volley.newRequestQueue(getApplicationContext());
nxtPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent startActivity = new Intent(SignUp.this, HomePage.class);
startActivity(startActivity);
sendData();
}
});
}
//public void GetData(){
// TempFname = Fname.getText().toString();
// TempLname = Lname.getText().toString();
// TempEmail = Email.getText().toString();
// TempPassword = Password.getText().toString();
// }
private void sendData(){
StringRequest request = new StringRequest(Request.Method.POST, sendURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONObject jobj = new JSONObject(response);
success = jobj.getInt(TAG_SUCCESS);
if(success == 1){
Toast.makeText(SignUp.this, jobj.getString(TAG_MESSAGE), Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(SignUp.this, jobj.getString(TAG_MESSAGE), Toast.LENGTH_SHORT).show();
}
}catch (Exception e){
Toast.makeText(SignUp.this, "Error Occured " + e, Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
Toast.makeText(SignUp.this, error.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
public Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("F_Name" , Fname.getText().toString());
params.put("L_Name" , Lname.getText().toString());
params.put("Email" , Email.getText().toString());
params.put("Password" , Password.getText().toString());
return params;
}
};
request.setRetryPolicy(new DefaultRetryPolicy(10000, 1, 1.0f));
requestQueue.add(request);
}
}
DatabaseConfig.php
<?php
$HostName = "localhost";
$HostUser = "tg322_admin";
$HostPass = "1234";
$DatabaseName = "tg322_AndroidAppDatabase";
$con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);
if(!$con){
echo "Error occured in connection";
}
?>
get_data.php
<?php
include "DatabaseConfig.php";
class user{}
$fname = ($_POST['F_Name']);
$lname = ($_POST['L_Name']);
$email = ($_POST['Email']);
$pass = ($_POST['Password']);
$query = "INSERT INTO 'Login_Details' ('id' , 'F_Name' , 'L_Name' , 'Email' , 'Password') values (NULL, '".$fname."' , '".$lname."' , '".$email."' , '".$pass."')";
mysqli_query($con,$query);
if($query){
$response=new user();
$response->success=1;
$response->message="Successfully uploaded";
die(json_encode($response));
}else{
$response=new user();
$response->success=0;
$response->message="Failed to upload";
die(json_encode($response));
}
mysqli_close($con);
?>
This is the result when running my app:
Error Occured org.json.JSONException: No value for Success
Edit
After adding error_reporting(E_ALL); to both php scripts, I am confident that the error does not lie with the php code as no error is being reported. {"success":1,"message":"Successfully uploaded"} This is the response from my php code so I am connecting to the database successfully but I am unsure what the issue is with my android studio code.

Can't delete and create data on Fragment Activity [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm trying to delete and create a data string from a API webpage but i can't get the error code
I create API website from native php. But i create data on postman work insert and delete data
Code Delete Data
package com.dev.kedaiit.sibooks.ui.kategori;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.dev.kedaiit.sibooks.MainActivity;
import com.dev.kedaiit.sibooks.R;
import com.dev.kedaiit.sibooks.util.AppController;
import com.dev.kedaiit.sibooks.util.ServerAPI;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class DeleteKategori extends AppCompatActivity {
EditText deleteID ;
Button btnDelete;
ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delete_kategori);
deleteID = (EditText) findViewById(R.id.id_kategori);
btnDelete = (Button) findViewById(R.id.btn_delete);
pd = new ProgressDialog(DeleteKategori.this);
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
deleteData();
}
});
}
private void deleteData()
{
pd.setMessage("Delete Data ...");
pd.setCancelable(true);
pd.show();
StringRequest delReq = new StringRequest(Request.Method.POST, ServerAPI.URL_DELETE_KATEGORI, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pd.cancel();
Log.d("volley","response : " + response.toString());
try {
JSONObject res = new JSONObject(response);
Toast.makeText(DeleteKategori.this,"Successs" +res.getString("message"), Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
startActivity(new Intent(DeleteKategori.this, KategoriFragment.class));
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pd.cancel();
Log.d("volley", "error : " + error.getMessage());
Toast.makeText(DeleteKategori.this, "ERROR DELETE DATA", Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
map.put("id_kategori",deleteID.getText().toString());
return map;
}
};
AppController.getInstance().addToRequestQueue(delReq);
}
}
Code Insert Data
package com.dev.kedaiit.sibooks.ui.kategori;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.dev.kedaiit.sibooks.R;
import com.dev.kedaiit.sibooks.util.AppController;
import com.dev.kedaiit.sibooks.util.ServerAPI;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class InsertKategori extends AppCompatActivity {
EditText id_kategori, kategori;
Button btnBatal, btnSimpan;
ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert_kategori);
/*get data from intent*/
Intent data = getIntent();
final int update = data.getIntExtra("update",0);
String intent_idkategori = data.getStringExtra("id_kategori");
String intent_kategori = data.getStringExtra("kategori");
/*end get data from intent*/
// id_kategori = (EditText) findViewById(R.id.idkategori);
kategori = (EditText) findViewById(R.id.edt_kategori);
btnBatal = (Button) findViewById(R.id.btn_cancel);
btnSimpan = (Button) findViewById(R.id.btn_simpan);
pd = new ProgressDialog(InsertKategori.this);
/*kondisi update / insert*/
if(update == 1)
{
btnSimpan.setText("Update Data");
id_kategori.setText(intent_idkategori);
id_kategori.setVisibility(View.VISIBLE);
kategori.setText(intent_kategori);
}
btnSimpan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(update == 1)
{
Update_data();
}else {
simpanData();
}
}
});
btnBatal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent main = new Intent(InsertKategori.this,KategoriFragment.class);
startActivity(main);
}
});
}
private void Update_data()
{
pd.setMessage("Update Data");
pd.setCancelable(true);
pd.show();
StringRequest updateReq = new StringRequest(Request.Method.POST, ServerAPI.URL_UPDATE_KATEGORI,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pd.cancel();
try {
JSONObject res = new JSONObject(response);
Toast.makeText(InsertKategori.this, ""+ res.getString("message") , Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
startActivity( new Intent(InsertKategori.this,KategoriFragment.class));
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pd.cancel();
Toast.makeText(InsertKategori.this, "Gagal Insert Data", Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> map = new HashMap<>();
map.put("id_kategori",id_kategori.getText().toString());
map.put("kategori",kategori.getText().toString());
return map;
}
};
AppController.getInstance().addToRequestQueue(updateReq);
}
private void simpanData()
{
pd.setMessage("Menyimpan Data");
pd.setCancelable(true);
pd.show();
StringRequest sendData = new StringRequest(Request.Method.POST, ServerAPI.URL_INSERT_KATEGORI,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pd.cancel();
try {
JSONObject res = new JSONObject(response);
Toast.makeText(InsertKategori.this, ""+ res.getString("message") , Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
startActivity( new Intent(InsertKategori.this,KategoriFragment.class));
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pd.cancel();
Toast.makeText(InsertKategori.this, "Gagal Insert Data", Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> map = new HashMap<>();
map.put("id_kategori",id_kategori.getText().toString());
map.put("kategori",kategori.getText().toString());
return map;
}
};
AppController.getInstance().addToRequestQueue(sendData);
}
}
Fragment Kategori
package com.dev.kedaiit.sibooks.ui.kategori;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.dev.kedaiit.sibooks.R;
import com.dev.kedaiit.sibooks.adapter.AdapterDataKategori;
import com.dev.kedaiit.sibooks.model.DataKategori;
import com.dev.kedaiit.sibooks.util.ServerAPI;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class KategoriFragment extends Fragment {
private RecyclerView recyclerView;
private FloatingActionButton floatingActionButton;
private LinearLayoutManager linearLayoutManager;
private DividerItemDecoration dividerItemDecoration;
private List<DataKategori> list;
private RecyclerView.Adapter adapter;
public KategoriFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_kategori, container, false);
recyclerView = view.findViewById(R.id.recyclerViewKategori);
list = new ArrayList<DataKategori>();
adapter = new AdapterDataKategori(getContext(), list);
linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(), linearLayoutManager.getOrientation());
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.addItemDecoration(dividerItemDecoration);
recyclerView.setAdapter(adapter);
FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab);
FloatingActionButton delKtg = (FloatingActionButton) view.findViewById(R.id.delKtg);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), InsertKategori.class);
startActivity(intent);
}
});
delKtg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(),DeleteKategori.class);
startActivity(intent);
}
});
getData();
return view;
}
private void getData() {
final ProgressDialog progressDialog = new ProgressDialog(getContext());
progressDialog.setMessage("Loading...");
progressDialog.show();
JsonObjectRequest my_request = new JsonObjectRequest(Request.Method.GET, ServerAPI.URL_DATA_KATEGORI, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try{
JSONArray jsonArray = response.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject Jobj = jsonArray.getJSONObject(i);
DataKategori obj = new DataKategori();
obj.setId_kategori(Jobj.getString("id_kategori"));
obj.setKategori(Jobj.getString("kategori"));
list.add(obj);
}
} catch (JSONException e) {
e.printStackTrace();
progressDialog.dismiss();
}
adapter.notifyDataSetChanged();
progressDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error: " + error.getMessage());
progressDialog.dismiss();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(my_request);
}
}
https://github.com/bellabeen/sibooks-client This project me get this in the logcat and when i dont get error code
Your code is almost fine. You just missed one thing. You did not initialize VolleyRequest. Inside simponData and UpdateData methods write this line at the bottom.
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(my_request);
instead of AppController.getInstance().addToRequestQueue(updateReq).
other thing is you are calling the fragment in intent from when response is received .You should call onbackPress() when result is recieved successfully.
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pd.cancel();
try {
JSONObject res = new JSONObject(response);
Toast.makeText(InsertKategori.this, ""+ res.getString("message") , Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
onBackPressed();
}
},
It will restore the previous fragment. In order to update the KategoriFragment view when successful response is received, you can call the getData() method in onResume() method instead of oncreate(). it will call this method whenever fragment is visible to the use

How to send Spinner selected value in database using wamp server

In this android code it is sending description in database but not sending Spinner value in database
package com.example.mis_internee.test;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.sql.SQLOutput;
import java.util.HashMap;
import java.util.Map;
public class atd_leave_form extends AppCompatActivity {
EditText Descr, lastname, age;
Button insert;
TextView back;
RequestQueue requestQueue;
String insertUrl = "http://192.168.0.102/A/issue.php";
// String showUrl = "http://192.168.1.65/tutorial/showStudents.php";
TextView TV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_atd_leave_form);
Descr = (EditText) findViewById(R.id.descText);
insert = (Button) findViewById(R.id.send);
TV = (TextView) findViewById(R.id.uname);
back = (TextView) findViewById(R.id.Back);
// TV= (TextView)findViewById(R.id.textView);
final Spinner staticSpinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> staticAdapter = ArrayAdapter.createFromResource(this, R.array.list,android.R.layout.simple_spinner_item);
staticAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
staticSpinner.setAdapter(staticAdapter);
// String name= "Username= "+getIntent().getExtras().getString("username");
// TV.setText(name);
// String name= "Username= "+getIntent().getExtras().getString("username");
// result.setText(name);
//
// back.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// Intent i = new Intent(atd_leave_form.this, MainActivity.class);
// startActivity(i);
//
//
// }
// });
requestQueue = Volley.newRequestQueue(getApplicationContext());
insert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String DESCR = Descr.getText().toString();
final String Spin = staticSpinner.getSelectedItem().toString();
StringRequest request = new StringRequest(Request.Method.POST, insertUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(Descr.getText().toString().equals("")){
Toast.makeText(getApplication(),"Please Enter Detail ",Toast.LENGTH_LONG).show();
}
else if(Descr.getText().toString().length()<10){
Toast.makeText(getApplication(),"Text Must be Greater Than 10",Toast.LENGTH_LONG).show();
}
else{
System.out.println(response.toString());
Toast.makeText(getApplication(),"Application Submitted Successfully....!",Toast.LENGTH_LONG).show();
Intent intent = new Intent(atd_leave_form. this, Issue.class);
startActivity(intent);
}
}}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> parameters = new HashMap<String, String>();
parameters.put("Descr",Descr.getText().toString());
parameters.put("Spin",staticSpinner.toString());
return parameters;
}
};
requestQueue.add(request);
}
});
}
}
i used spinner and select value and submit it but no error with submission description in database. i am using oracle web services with wamp server, but description submitting spinner value is not.
thanks in advance
use staticSpinner.getSelectedItem().toString() instead of staticSpinner.toString() in posting parameters
you are posting wrong data check below code
insert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String DESCR = Descr.getText().toString();
final String Spin = staticSpinner.getSelectedItem().toString();
StringRequest request = new StringRequest(Request.Method.POST, insertUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(Descr.getText().toString().equals("")){
Toast.makeText(getApplication(),"Please Enter Detail ",Toast.LENGTH_LONG).show();
}
else if(Descr.getText().toString().length()<10){
Toast.makeText(getApplication(),"Text Must be Greater Than 10",Toast.LENGTH_LONG).show();
}
else{
System.out.println(response.toString());
Toast.makeText(getApplication(),"Application Submitted Successfully....!",Toast.LENGTH_LONG).show();
Intent intent = new Intent(atd_leave_form. this, Issue.class);
startActivity(intent);
}
}}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> parameters = new HashMap<String, String>();
parameters.put("Descr",Descr.getText().toString());
parameters.put("Spin",Spin);//change here
return parameters;
}
};
requestQueue.add(request);
}
});
}
}

java.io.ioexception unexpected end of stream on com.android.okhttp.address #f32949bd

Hello , I am making a android application using Mysql database , where i am trying to make registration of the user !! can anyone help me plz
i am getting this error when i click on Register button : java.io.ioexception unexpected end of stream on com.android.okhttp.address #f32949bd
This is my code :
package androidloginandregistration.inducesmile.com.enpascheres;
/**
* Created by User on 10/12/2017.
*/
public class Constants {
public static final String ROOT_URL ="http://192.168.1.3/android/v1/registerUser.php";
public static final String URL_REGISTER = ROOT_URL+"registerUser.php";
}
and this is the main activity:
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private EditText editTextUsername,editTextEmail,editTextPassword;
private Button buttonRegister;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextEmail=(EditText)findViewById(R.id.editTextEmail);
editTextUsername=(EditText)findViewById(R.id.editTextUsername);
editTextPassword=(EditText)findViewById(R.id.editTextPassword);
buttonRegister=(Button)findViewById(R.id.buttonRegister);
progressDialog = new ProgressDialog(this);
buttonRegister.setOnClickListener(this);
}
private void registerUser(){
final String email= editTextEmail.getText().toString().trim();
final String username= editTextUsername.getText().toString().trim();
final String password= editTextPassword.getText().toString().trim();
progressDialog.setMessage("Registering user ...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST,
Constants.URL_REGISTER,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject= new JSONObject(response);
Toast.makeText(getApplicationContext(),jsonObject.getString("message"),Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.hide();
Toast.makeText(getApplicationContext(),error.getMessage(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("username",username);
params.put("email",email);
params.put("password",password);
return params;
}
};
RequestQueue requestQueue= Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
#Override
public void onClick(View view) {
if(view==buttonRegister)
registerUser();
}
}

How to edit paypal activities layout

I am using com.paypal.android.MEP.PayPalActivity library. I want to edit layout but I can't access it. How can I edit default layout of this library. I am trying to transfer money from an account to another account. It works correctly but user interface seems bad
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.paypal.android.MEP.CheckoutButton;
import com.paypal.android.MEP.PayPal;
import com.paypal.android.MEP.PayPalActivity;
import com.paypal.android.MEP.PayPalAdvancedPayment;
import com.paypal.android.MEP.PayPalPayment;
import com.paypal.android.MEP.PayPalReceiverDetails;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import project.com.holobech.MainActivity;
import project.com.holobech.R;
import project.com.holobech.app.AppConfig;
import project.com.holobech.app.AppController;
import project.com.holobech.model.UserList;
import project.com.holobech.util.PaypalUtil;
public class PaypalActivity extends ActionBarActivity {
// LogCat tag
private static final String TAG = PaypalActivity.class.getSimpleName();
public final int PAYPAL_RESPONSE = 100;
TextView txtOdullendirEmail;
TextView txtOdullendirAmount;
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_paypal);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
txtOdullendirEmail = (TextView) findViewById(R.id.txt_odullendir_email);
txtOdullendirEmail.setText("Ödüllendirilecek E-Posta : " + ProfileFragment.email);
txtOdullendirAmount= (TextView) findViewById(R.id.txt_odullendir_amount);
txtOdullendirAmount.setText("Ödüllendirilecek Miktar : 1$");
Button paypal_button = (Button) findViewById(R.id.paypal_button);
initLibrary();
paypal_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// pay integration here
PayPalButtonClick(ProfileFragment.email, "1");
}
});
}
public void initLibrary() {
PayPal pp = PayPal.getInstance();
if (pp == null) {
pp = PayPal.initWithAppID(this, PaypalUtil.paypal_liv_id,
PayPal.ENV_LIVE);
}
}
public void PayPalButtonClick(String primary_id, String primary_amount) {
// Create a basic PayPal payment
// PayPalPayment newPayment = new PayPalPayment();
// newPayment.setSubtotal(new BigDecimal("1.0"));
// newPayment.setCurrencyType("USD");
// newPayment.setRecipient("npavankumar34#gmail.com");
// newPayment.setMerchantName("My Company");
// Log.d("pavan", "calling intent");
// if( PayPal.getInstance()!=null){
// Log.d("pavan", "in if");
// Intent paypalIntent = PayPal.getInstance().checkout(newPayment,
// this);
// startActivityForResult(paypalIntent, 1);
//
// config reciever1
PayPalReceiverDetails receiver0;
receiver0 = new PayPalReceiverDetails();
receiver0.setRecipient(primary_id);
receiver0.setSubtotal(new BigDecimal(primary_amount));
// adding payment type
PayPalAdvancedPayment advPayment = new PayPalAdvancedPayment();
advPayment.setCurrencyType("TRY");
advPayment.getReceivers().add(receiver0);
Intent paypalIntent = PayPal.getInstance().checkout(advPayment, this);
this.startActivityForResult(paypalIntent, PAYPAL_RESPONSE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d("pavan", "response");
if (requestCode == PAYPAL_RESPONSE) {
switch(resultCode) {
case Activity.RESULT_OK:
//The payment succeeded
String payKey =
data.getStringExtra(PayPalActivity.EXTRA_PAY_KEY);
Log.d("pavan", "success "+payKey);
Toast.makeText(getApplicationContext(), "Payment done succesfully ", Toast.LENGTH_LONG).show();
setMoneyTransfer();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getApplicationContext(), "Payment Canceled , Try again ", Toast.LENGTH_LONG).show();
break;
case PayPalActivity.RESULT_FAILURE:
Toast.makeText(getApplicationContext(), "Payment failed , Try again ", Toast.LENGTH_LONG).show();
break;
}
}
}
private void setMoneyTransfer() {
// istek iptali için tag
String tag_string_req = "req_money_transfer";
pDialog.setMessage("Lütfen bekleyin...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.URL_CONTEST, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Para transferi yanıtı : " + response.toString());
hideDialog();
try{
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// json hatası kontrolü
if (!error) {
// başarılı
Log.d("Response", response.toString());
} else {
// başarısız
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON hatası
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Para transferi Hatası: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// login urle bilgileri gönder
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "money_transfer");
params.put("sender", MainActivity.PROFILE_EMAIL);
params.put("receiver", ProfileFragment.email);
return params;
}
};
// istek kuyruğuna isteği ekle
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
This checkout page layout is default and there is no way you can edit the layout.

Categories

Resources