volley timeout error...Data inserting two times - java

I m getting volley timeout error every time i try to insert data..Despite of the error, the data is inserted correctly but its inserting two times every time i press the button.
I need to remove the error and insert data only once. Also it takes too much time after clicking button to display error.
package com.example.sumit.myapplication;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.CardView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
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 com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.MutableData;
import com.google.firebase.database.Transaction;
import com.google.firebase.database.ValueEventListener;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Sumit on 20-02-2018.
*/
public class register extends Fragment{
RequestQueue requestQueue;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
View v = inflater.inflate(R.layout.login,container,false);
return v;
}
public void onCreate(Bundle savedInstancesState)
{
super.onCreate(savedInstancesState);
TextView t = (TextView) ((MainActivity) getActivity()).findViewById(R.id.textView3);
t.setText("Register");
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
final View vt = super.getView();
final CardView b=(CardView)vt.findViewById(R.id.cardView);
final TextView txt = (TextView)vt.findViewById(R.id.uid);
final EditText txt1 = (EditText) vt.findViewById(R.id.editText);
final EditText txt2 = (EditText) vt.findViewById(R.id.editText2);
final EditText txt3 = (EditText) vt.findViewById(R.id.editText3);
final EditText txt4 = (EditText) vt.findViewById(R.id.editText4);
final Spinner hostel1=(Spinner) vt.findViewById(R.id.spinner1);
final Spinner branch1=(Spinner) vt.findViewById(R.id.spinner2);
final String HttpUrl = "https://testzineapp.000webhostapp.com/insert_record.php";
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View vt) {
final String id=txt1.getText().toString().trim();
final String name=txt2.getText().toString().trim();
final String number=txt3.getText().toString().trim();
final String email=txt4.getText().toString().trim();
final String hostel=hostel1.getSelectedItem().toString().trim();
final String branch=branch1.getSelectedItem().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, HttpUrl,
new Response.Listener<String>() {
#Override
public void onResponse(String ServerResponse) {
// Showing response message coming from server.
Toast.makeText(getContext(), ServerResponse, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
// Showing error message if something goes wrong.
Toast.makeText(getContext(), volleyError.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Creating Map String Params.
Map<String, String> params = new HashMap<String, String>();
// Adding All values to Params.
params.put("College_ID", id);
params.put("Name", name);
params.put("Mobile_Number", number);
params.put("Email_ID", email);
params.put("Hosteller", hostel);
params.put("Branch", branch);
return params;
}
};
// Creating RequestQueue.
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
// Adding the StringRequest object into requestQueue.
requestQueue.add(stringRequest);
txt1.setText("");
txt2.setText("");
txt3.setText("");
txt4.setText("");
};
});
super.onViewCreated(view, savedInstanceState);
}
}

Because of volley default retry policy your your request is processing two times, try this code to avoid it.
stringRequest.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(_context);
requestQueue.add(stringRequest);

Related

android studio com.android.volley.clienterror

its giving me a error that is called com.android.volley.clienterror
whenever i press the register or login button. I imagine that the
error could be that my android app isnt connected to my database but
idk.................................................................................................................................................................................................................
import android.content.Intent;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
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 java.util.HashMap;
import java.util.Map;
public class register extends AppCompatActivity {
private EditText etName, etEmail, etPassword, etReenterPassword;
private TextView tvStatus;
private Button btnRegister;
private String URL = "http://10.0.2.2/login.register.php";
private String name, email, password, reenterPassword;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
etName = findViewById(R.id.etName);
etEmail = findViewById(R.id.etEmail);
etPassword = findViewById(R.id.etPassword);
etReenterPassword = findViewById(R.id.etReenterPassword);
tvStatus = findViewById(R.id.tvStatus);
btnRegister = findViewById(R.id.btnRegister);
name = email = password = reenterPassword = "";
}
public void save(View view){
name = etName.getText().toString().trim();
email = etEmail.getText().toString().trim();
password = etPassword.getText().toString().trim();
reenterPassword = etReenterPassword.getText().toString().trim();
if(!password.equals(reenterPassword)){
Toast.makeText(this , "Password mismatch", Toast.LENGTH_SHORT).show();
}
else if(!name.equals("")&& !email.equals("") && !password.equals("")){
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.equals("success")) {
tvStatus.setText("Successfully registered");
btnRegister.setClickable(false);
} else if (response.equals("failure")) {
tvStatus.setText("something went wrong!");
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.toString().trim(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> data = new HashMap<>();
data.put("name", name);
data.put("email", email);
data.put("password", password);
return data;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
}
public void login(View view){
Intent intent = new Intent (this, MainActivity.class);
startActivity(intent);
finish();
}
}

Android studio parsing json object

i have a issue with my code in android studio. the url of json object is not been open. when i change the url for testing whether there is any problem with my code or not, it is ok. and the only diffrence between those two urls is one of them is https (which run without any problem) and the other is http (which is not working). how can i run the code with out problem?
package com.example.chatbot;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
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 org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View view){
TextView textView = findViewById(R.id.textView);
String input = textView.getText().toString();
//textView.setText(" ");
TextView out=findViewById(R.id.outPut);
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
String url ="http://api.brainshop.ai/get?bid=159114&key=OCfIpglFJbfXDt2G&uid=[uid]&msg=[msg]=hello";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//set the text
String res = response.toString();
Toast.makeText(MainActivity.this,response.toString(),Toast.LENGTH_SHORT).show();
out.setText(res);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(request);
}
}
You should set "android:usesCleartextTraffic" flag to true in your AndroidManifest file.
Since target api 28 it defaults to false. more info here

How to create Quiz app using Volley library

I am creating quiz app from volley library in android. where I get data in Array list from external website. now problem is that how to set data in Textview and Buttons. I created one Textviewfor show question, four Buttions for options, and Two more Buttions for go to next question and go to previous question. here is image
I want that when i click one of the option button than his color will be blue and rest of button will be grey. when i click next button than load new question and all options button will be grey.
here is my main activity.java code. please help me in create quiz app.
package com.ravindra.excelrecycleview;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.ProgressDialog;
import android.os.Bundle;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URL;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private QuestionAdapter mQuestionAdatpter;
private ArrayList<question> mquestion;
private RequestQueue mRequestQueue;
ProgressDialog loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recylcer_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mquestion = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
parseJSON();
}
private void parseJSON(){
loading = ProgressDialog.show(this,"Loading","please wait",false,true);
String url ="https://script.google.com/macros/s/AKfycbw6eHqtKTxHoS9HPSdfTasY-iebLQXUgS3sHHiOpeuGxJfssBI/exec?action=getQuestions";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("items");
for (int i =0;i<jsonArray.length();i++){
JSONObject items = jsonArray.getJSONObject(i);
String questions = items.getString("questions");
String optiona = items.getString("optiona");
String optionb = items.getString("optionb");
String optionc = items.getString("optionc");
String optiond = items.getString("optiond");
String correctans = items.getString("correctans");
String explain = items.getString("explain");
mquestion.add(new question(questions,optiona,optionb,optionc,optiond,correctans,explain));
}
mQuestionAdatpter = new QuestionAdapter(MainActivity.this,mquestion);
mRecyclerView.setAdapter(mQuestionAdatpter);
loading.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
} );
mRequestQueue.add(request);
int socketTimeOut = 50000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeOut, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
request.setRetryPolicy(policy);
}
}

volley post arrayrequest not working

I tried to create code to get all users from my server except me.
It is not jumping to the #overwrite response.
I hope sombody can help me.
I was looking now for days why it's not working
XD didnt found the prob.
My php code:
<?php
$con = mysqli_connect("localhost", "userID", "password", "database");
$name = $_POST["name"];
$passwort = $_POST["passwort"];
$statement = mysqli_prepare($con, "SELECT * FROM user WHERE name = ? AND passwort = ?");
mysqli_stmt_bind_param($statement, "ss", $name, $passwort);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $userID, $name, $vorname, $nachname, $passwort);
$response = array();
$response["success"] = false;
while(mysqli_stmt_fetch($statement)){
$response["success"] = true;
$response["name"] = $name;
$response["vorname"] = $vorname;
$response["nachname"] = $nachname;
$response["passwort"] = $passwort;
}
echo json_encode($response);
?>
In JAVA they all come together:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Adapter;
import android.widget.ListView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.example.android.app.Data.LoginRequest;
import com.example.android.app.Data.RegistryRequest;
import com.example.android.app.Data.UserlistRequest;
import com.example.android.app.Tools.User;
import com.example.android.app.Tools.UserAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Map;
public class listeAndererActivity extends AppCompatActivity {
private String Tag="lsiteanderer";
private ArrayList<User> userListe = new ArrayList<>();
private UserAdapter useradapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_liste_anderer);
String ownname="juli";
/////VERSION 2///////////////////////////////////////////////////////////////
Response.Listener<JSONArray> responseListenerJSONArray=new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject obj = response.getJSONObject (i);
User user = new User (obj.getString ("name"),obj.getInt("user_id"));
Log.v(Tag, "name in der for schlife ist"+user.getName());
userListe.add(user);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
useradapter=new UserAdapter(this, userListe);
UserlistRequest userlistRequest = new UserlistRequest(ownname, responseListenerJSONArray);
RequestQueue queue= Volley.newRequestQueue(listeAndererActivity.this);
queue.add(userlistRequest);
ListView listView = (ListView) findViewById(R.id.AndererListe);
listView.setAdapter(useradapter);
}
}
My Reqest Class:
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONArray;
import java.lang.reflect.Array;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Juli on 17.12.2017.
*/
public class UserlistRequest extends JsonArrayRequest {
private static final String userlistRequestUrl="https://unityentertainment.000webhostapp.com/OtherUser.php";
private Map<String,String> params;
public UserlistRequest(String name, Response.Listener<JSONArray> listener){
super(Request.Method.POST, userlistRequestUrl, listener, null);
params= new HashMap<>();
params.put("name", name);
}
// public UserlistRequest(String ownname, Listener<JSONArray> responseListenerJSONArray) {
// super();
// }
#Override
public Map<String, String> getParams() {
return params;
}
}
My Data Class:
public class User {
private String name;
private int user_id;
public User(String name, int user_id){
this.name=name;
this.user_id=user_id;
}
public String getName() {
return name;
}
public int getUser_id() {
return user_id;
}
}
My Adapter:
import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.volley.Response;
import com.example.android.app.R;
import com.example.android.app.ListeAndererActivity;
import java.util.ArrayList;
public class UserAdapter extends ArrayAdapter<User> {
public UserAdapter(ListeAndererActivity activity, ArrayList<User> userArrayList) {
super((Context) activity, 0 ,userArrayList);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Check if the existing view is being reused, otherwise inflate the view
View listItemView = convertView;
if(listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.itemlist_user, parent, false);
}
// Get the {#link AndroidFlavor} object located at this position in the list
User currentAndroidFlavor = getItem(position);
// Find the TextView in the list_item.xml layout with the ID version_name
TextView nameTextView = (TextView) listItemView.findViewById(R.id.itemlistUser_TextView);
// Get the version name from the current AndroidFlavor object and
// set this text on the name TextView
nameTextView.setText(currentAndroidFlavor.getName());
return listItemView;
}
}
you should track your request and response and see where it stops. Use somthing like postman or some firefox/chrome plugin to test the back end php rest API part of your code and narrow down the possibilities and also monitor the testing device log by printing values and look where your code is stopping or behave different than intended.
from my opinion you should first use api testing softwares like postman.
postman is great for that.
also this worked for me
$stmt=$db->prepare("SELECT * FROM search WHERE designation LIKE ?");
$stmt->bind_param("s",$a);
$stmt->execute();
$d=$stmt->get_result();
while($b=$d->fetch_array(MYSQLI_ASSOC)){
$result[]=$b;
}
//you could then do something like this
$response['test']=$result;
echo json_encode($result);
I did like below:
public class UserlistRequest extends JsonArrayRequest {
private static final String userlistRequestUrl="https://unityentertainment.000webhostapp.com/OtherUser.php";
private Map<String,String> params;
public UserlistRequest(String name, Response.Listener<JSONArray> listener) {
super(Method.POST, userlistRequestUrl, (String) null, listener, null);
// public UserlistRequest(String name, Response.Listener<JSONArray> listener){
// super(Request.Method.POST, userlistRequestUrl, listener, null);
params= new HashMap<>();
params.put("name", name);
params.put("name", name);
}
// public UserlistRequest(String ownname, Listener<JSONArray> responseListenerJSONArray) {
// super();
// }
#Override
public Map<String, String> getParams() {
return params;
}
}
But it doesn't use the getparams

How to add JSON data to RecyclerView

This is my RecyclerAdapter code:
package com.example.sander.app;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by Sander on 6-4-2017.
*/
public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.MyViewHolder> {
private String[] mDataset;
ArrayList<String> ArrayDataset;
public static class MyViewHolder extends RecyclerView.ViewHolder{
public CardView mCardView;
public TextView mTextView;
public MyViewHolder(View v){
super(v);
mCardView = (CardView) v.findViewById(R.id.card_view);
mTextView = (TextView) v.findViewById(R.id.tv_blah);
}
}
public RecycleAdapter(ArrayList<String> names){
ArrayDataset = names;
}
#Override
public RecycleAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_card_view, parent, false);
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position){
holder.mTextView.setText(ArrayDataset.get(position));
}
#Override
public int getItemCount() { return ArrayDataset.size(); }
}
And this is my Recycler Fragment code:
package com.example.sander.app;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
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.ArrayList;
import java.util.List;
/**
* Created by Sander on 6-4-2017.
*/
public class RecycleFrame extends Fragment {
ArrayList<String> names = new ArrayList<>();
GoogleMaps maps = new GoogleMaps();
public RecycleFrame() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RequestQueue rq = Volley.newRequestQueue(getActivity().getApplicationContext());
String url= "http://test.dontstealmywag.ga/api/parkgarage.php";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Do something with the response
try{
JSONObject o = new JSONObject(response);
JSONArray values=o.getJSONArray("parkgarage");
for ( int i=0; i< values.length(); i++) {
JSONObject jsonObject = values.getJSONObject(i);
names.add(jsonObject.getString("parkgarage_name"));
}
} catch (JSONException ex){}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle error
}
});
rq.add(stringRequest);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_recycle, container, false);
RecyclerView VRecyclerView = (RecyclerView) rootView.findViewById(R.id.rv_recycler_view);
VRecyclerView.setHasFixedSize(true);
RecycleAdapter adapter = new RecycleAdapter(names);
VRecyclerView.setAdapter(adapter);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
VRecyclerView.setLayoutManager(llm);
return rootView;
}
}
Now if I'm correct. My data from my API (link can be found in the code), will be added in an ArrayList called "names", but when I run my code my Recyclerview is empty. How do I add my JSON data to the RecyclerView and display it.
(For the record if I try it with String [] {"Example"} it will show a card with "Example")
Thanks in advance

Categories