#java #android #android-volley
Вопрос:
Когда я нажимаю на кнопку «Регистрация», происходит эта ошибка.
Я установил залп 1.1.1
это мой код:
public class MainActivity extends AppCompatActivity {
private EditText etEmail, etPassword;
private String email, password;
private String URL = "http://10.0.2.2/login/login.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
email = password = "";
etEmail = findViewById(R.id.etEmail);
etPassword = findViewById(R.id.etPassword);
}
public void login(View view) {
email = etEmail.getText().toString().trim();
password = etPassword.getText().toString().trim();
if(!email.equals("")amp;amp;!password.equals("")){
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if (response.equals("success")) {
Intent intent = new Intent(MainActivity.this, Success.class);
startActivity(intent);
finish();
} else if (response.equals("failure")) {
Toast.makeText(MainActivity.this, "Invalid Login Id/Password", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString().trim(), Toast.LENGTH_SHORT).show();
}
}){
protected Map<String, String> getParms() throws AuthFailureError {
Map<String, String> parms = new HashMap<>();
parms.put("email",email);
parms.put("password", password);
return parms;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}else{
Toast.makeText(this, "Fields can not be empty!", Toast.LENGTH_SHORT).show();
}
}
Комментарии:
1. Изображения нет в вашем вопросе. Можете ли вы скопировать и вставить полученную ошибку ?
2. Пожалуйста, проясните вашу конкретную проблему или предоставьте дополнительные сведения, чтобы точно указать, что вам нужно. Поскольку это написано в настоящее время, трудно точно сказать, о чем вы просите.
3. я добавил изображение, чтобы быть понятным для вас, ребята
4. Вместо того , чтобы просто предоставлять a
Toast
, вам действительно следует зарегистрировать трассировку стека исключений и проверить logcat, чтобы узнать, что в нем написано.
I would like to know how I can rectify this issue. Research and replacement of code has been done however the problem persists.
Here is my code working with volley.
private void Regist(){
loading.setVisibility(View.VISIBLE);
btn_regist.setVisibility(View.GONE);
final String name = this.name.getText().toString().trim();
final String email = this.email.getText().toString().trim();
final String password = this.password.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_REGIST,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try{
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
if(success.equals("1")) {
Toast.makeText(RegisterActivity.this, "Register Success!", Toast.LENGTH_SHORT).show();
}
}catch (JSONException e) {
e.printStackTrace();
Toast.makeText(RegisterActivity.this, "Register Error!" + e.toString(), Toast.LENGTH_SHORT).show();
loading.setVisibility(View.GONE);
btn_regist.setVisibility(View.VISIBLE);
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(RegisterActivity.this, "Register Error!" + error.toString(), Toast.LENGTH_SHORT).show();
loading.setVisibility(View.GONE);
btn_regist.setVisibility(View.VISIBLE);
}
})
{
@Override
protected Map<String, String> getParams()throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("name", name);
params.put("email", email);
params.put("password", password);
return super.getParams();
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
Since I receive ‘com.android.volley.ClientError’ I assume this is wrong but if you require the rest of the code please comment!
Содержание
- ERROR- com.android.volley.ClientError #278
- Comments
- Footer
- Android: Как обрабатывать сообщение об ошибке с сервера с помощью Volley?
- 2 ответов:
- Использование библиотеки Volley в Android на примере получения данных из погодного API
- Volley library not working on Android 9.0 #235
- Comments
- Android Clarified
- Android Explained in Simple Terms
- Android Volley example with Error Handling
when im trying to send my data to server i get message from onErrorResponse
com.android.volley.ClientError
The text was updated successfully, but these errors were encountered:
It means the server returned a 4xx error code.
throw new ClientError ( networkResponse );
@Alireza-hr have you got the error cleared?
i’m also having the same error.
@Alireza-hr Could you please explain me how to solve this issue?
same issue.anyone can help ?
same issue with me can anyone tel how to resolve the android.volley.clienterror
Hey!!
I solved out the problem:
Change this code —
< @Override public Map getHeaders() < Map params = new HashMap<>(); params.put(«Content-Type», «application/json»); params.put(«Authorization», «Bearer » + Utils.readSharedSetting(context, «access_token», «»)); return params; >
with this:
<
@OverRide
public Map getParams() throws AuthFailureError <
Map params = new HashMap<>();
params.put(«Content-Type», «application/json»);
params.put(«Authorization», «Bearer » + Utils.readSharedSetting(context, «access_token», «»));
return params;
>
then it will work fine.
Thank you!!
can you tell me what is Utils
@manjirikolte
Hi 🙂
I always create a shared Utils class for the most commonly used function.
in my case i was missing some parameters required to be send but, it must be more clear for us
© 2023 GitHub, Inc.
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Источник
Android: Как обрабатывать сообщение об ошибке с сервера с помощью Volley?
Я использую волейбол для моего приложения для Android, чтобы получить данные с моего сервера. Он работает хорошо, за исключением обработки ошибки с моего сервера. Мой сервер отправляет этот ответ, когда есть ошибка:
моя цель-получить сообщение, а затем отобразить его в Toast . Я следовал за некоторым образцом, как это сделать, но это не работает.
есть моя ошибка слушателя:
и там результат моего отладчик : testerror﹕ 400 [[email protected]
EDIT: более того моя ошибка.getMessage () имеет значение null.
поэтому я не понимаю, почему мой переменный ответ.данные не ответ от моего сервера.
Если кто-то знает, как я могу получить сообщение с моего сервера, это будет круто.
2 ответов:
я реализовал нечто подобное этому, и это относительно просто. Ваше сообщение журнала печатает то, что выглядит как тарабарщина, потому что response.data — это действительно массив байтов — не String . Кроме того, VolleyError это действительно лишь затянувшийся Exception , так что исключение.getMessage () скорее всего не вернет то, что вы ищете, если вы не переопределите методы разбора для разбора вашего VolleyError в расширенном Request класса. Очень простой способ справиться с этим будет делать что-то вроде:
если вы добавите это в свой расширенный Request классов, getMessage() должны, по крайней мере, не возвращать null. Я обычно не очень беспокоюсь об этом, хотя, так как это достаточно легко сделать все это изнутри вашего onErrorResponse(VolleyError e) метод.
вы должны использовать библиотеку JSON для упрощения вещей — я использую Gson например, или вы можете использовать Apache JSONObject s, которые не должны требовать дополнительной внешней библиотеки. Первый шаг состоит в том, чтобы получить ответ JSON отправляется с вашего сервера как String (аналогично тому, что я только что продемонстрировал), далее вы можете дополнительно преобразовать его в JSONObject (используя либо apache JSONObject s и JsonArray s, или другая библиотека по вашему выбору) или просто разобрать String себя. После этого вам просто нужно отобразить Toast .
вот пример кода, чтобы вы начали:
попробуйте этот класс для обработки всех erros
Источник
Использование библиотеки Volley в Android на примере получения данных из погодного API
Каждому Android-разработчику рано или поздно приходится работать с сетью. В Android есть множество библиотек с открытым исходным кодом, таких как Retrofit, OkHttp или, например, Volley, на которой мы сегодня остановимся подробнее.
Итак, что же эта библиотека из себя представляет?
Volley — это HTTP-библиотека, которая упрощает и ускоряет работу в сети для приложений Android.
Код библиотеки на GitHub .
Итак, для начала работы с Volley нам необходимо добавить её в build.gradle(module:app):
Также необходимо добавить разрешение на использование интернета в манифесте нашего приложения:
Далее нам понадобится API. В данном туториале я воспользуюсь погодным API с сайта openweathermap.org/api .
Для начала создадим простую разметку для отображения данных, взятых из API (Application programming interface).
Далее заходим в MainActivity и создаем необходимые поля:
Инициализируем созданные поля поля в onCreate:
Теперь подходим к основной теме данного туториала — получение данных из API при помощи библиотеки Volley:
1) В MainActivity создаем метод GetWeather:
для приведения json’а в нормальный вид использован jsonformatter
Стоит заметить, что имена объектов должны быть записаны точно так же, как и в нашем API, иначе они просто не ‘достанутся’.
2) Создаем, непосредственно, метод setValues:
3) Вызываем методы getWeather() и setValues() в onCreate():
Источник
Volley library not working on Android 9.0 #235
I have two testing phones one is on 8.1 and the other one is on 9.0 volley is working fine on 8.1 but on 9.0 it’s giving null in Volley Error I traced it its network issue. My Volley version is 1.1.1
How can I solve this any help would be appreciated.
The text was updated successfully, but these errors were encountered:
I’m having the same issue. Getting an error like this:
E/Volley: [19988] NetworkDispatcher.run: Unhandled exception java.lang.RuntimeException: Stub! java.lang.RuntimeException: Stub! at org.apache.http.ProtocolVersion. (ProtocolVersion.java:6) at com.android.volley.toolbox.HurlStack.performRequest(HurlStack.java:148) at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:97) at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:118)
Hi @mostafaaddam
I Found the solution:
change your buildToolsVersion to ‘28.0.2’ and compileSdkVersion to 27 and try again. My issue has been resolved.
@rahulupadhyay thank you I did what you said I lowered my build tool version and the compiled version to 27 and it worked so the problem is from android 9.0 or 28 Volley is yet not compatible.
But thanks.
Can someone attach an example project which breaks when building with compileSdkVersion 28? It is working fine for me. The stack trace in the above comment doesn’t make sense, because line 148 of HurlStack has nothing to do with ProtocolVersion — are you using an older version of Volley?
In general Apache HTTP has been removed from Android 9. You might be hitting this: https://developer.android.com/about/versions/pie/android-9.0-changes-all#apache-nonp
I could not reproduce this issue with v1.1.1 nor v1.1.0 when targetSdk=28.
I also think the issue is because of using older version of Volley.
If you want a simple project using v1.1.1 with targetSdk=28, here is one.
Funny thing I posted this last month and had my issue instantly closed. But Im glad its getting attention. My project has been on hold because of this.
I’ve made an example app below showing Volley can load image on Android 8.1 but not on Android 9. Haven’t got time investigating it but suspect cache control issue.
A similar problem here. My app has been working fine until the first install in a v9.0 today (a Huawei Mate 20). My app has stopped connecting to my server using Volley:
String LOGIN_URL = «http://xxx.dyndns-ip.com:50547/../login.php»;
String url = LOGIN_URL + «?usuario=» + usuario + «&password=» + password;
jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener() <.
.
.
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(5000, 2, 1));
jsonObjectRequest.setShouldCache(false);
queue.add(jsonObjectRequest);
—> Triggers the «onErrorResponse».
It seems like a number of potential issues have come up here — let me try my best to address them all.
@arachaic your issue (#226) was closed because I do not believe it to be an issue specific to Volley, but rather any network-using app that targets API level 28 or higher. Cleartext traffic is disabled by default for such apps; you either need to switch to HTTPS everywhere or opt out for any cleartext sites you’d like to access. Please see this doc for more details.
Also note that while I do take an aggressive approach to closing issues when I believe they are fully addressed, I mean no personal offense by doing this, and I am always happy to reopen issues if more details can be provided that merit investigation.
@mktsui Based on the issue description you appear to be running into the same issue. The image that fails to load is at an HTTP URL; the one that succeeds is an HTTPS URL. If you would like to be able to access HTTP URLs, you will need a network policy that permits it as this is disabled by default when apps target SDK 28 or above. (Of course, you should try to avoid HTTP URLs for security/privacy reasons if it is feasible to do so).
@salvagp7500 there’s not enough information for us to investigate here from this alone. What I’d recommend you do is file a separate bug with more details, ideally including sample code, and the logs, including the full stack trace of the error passed to onErrorResponse. You should also mention whether this is specific to this particular device or if it can be reduced on an Android emulator, as this could be an OEM-specific issue on Huawei devices; I can’t say from what’s been provided here.
I’m going ahead and closing this issue out as I believe there are no pending issues here. But as always, if you are running into a problem, please file a bug with the details needed for us to reproduce or at least investigate, and we’ll be happy to take a look.
Источник
Android Clarified
Android Explained in Simple Terms
Android Volley example with Error Handling
In my previous post we learnt how to send GET,POST request using volley in Android. As we had seen every Volley requests has two callbacks -one for success and one for failure. While this might make sense if the request is successful but would lead to confusion if the error callback is called- as the developer doesn’t know why the request actually failed. A request could fail due to multiple reasons
- No internet connection
- Very slow internet connection- com android volley timeoutError
- An expired login session- com volley android volley AuthfailureError
- Server is down or is unable to process the request- com android volley ServerError
- Client not able to parse(read) the response
With these many reasons invoking the error callback it becomes difficult for both the developer and the user to figure out why a particular request failed. And this is what we going to resolve today.
The VolleyError object returned along with the error callback will be helping us to figure out why a particular request failed.
Once we know why a request failed logging it and displaying a appropriate error message will not only be great user experience but will also lead the user to resolve the issue on his own rather than being stuck (User can switch to a different network once he sees his current network is too slow). Logging the error encountered could help the developers in debugging
If you want to have a look at complete working example of Volley. Please refer this article ->Volley Example
Источник
Getting the Error below while using Android-Volley in android. The same problem remains unsolved here too…
08-27 14:46:18.779 26990-26990/com.rev.volleydemo D/VOLLEY﹕ http://api.androidhive.info/volley/person_object.json
08-27 14:46:18.879 26990-27004/com.rev.volleydemo E/Volley﹕ [619] NetworkDispatcher.run: Unhandled exception java.lang.RuntimeException: Bad URL null
java.lang.RuntimeException: Bad URL null
at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:151)
at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:114)
Caused by: java.net.MalformedURLException
at java.net.URL.<init>(URL.java:154)
at java.net.URL.<init>(URL.java:127)
at com.android.volley.toolbox.HurlStack.performRequest(HurlStack.java:102)
at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:97)
at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:114)
public class AppController extends Application {
public static final String TAG = AppController.class
.getSimpleName();
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static AppController mInstance;
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
mImageLoader = new ImageLoader(this.mRequestQueue,
new BitmapCache());
}
return this.mImageLoader;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
public class MainActivity extends AppCompatActivity {
public final String URL = new String("http://api.androidhive.info/volley/person_object.json");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("VOLLEY", URL);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Method.POST, null, URL, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("VOLLEY", response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("VOLLEY", error.toString());
}
});
AppController.getInstance().addToRequestQueue(jsonObjectRequest, "JSON_OBJ");
}
}
Getting the Error below while using Android-Volley in android. The same problem remains unsolved here too…
08-27 14:46:18.779 26990-26990/com.rev.volleydemo D/VOLLEY﹕ http://api.androidhive.info/volley/person_object.json
08-27 14:46:18.879 26990-27004/com.rev.volleydemo E/Volley﹕ [619] NetworkDispatcher.run: Unhandled exception java.lang.RuntimeException: Bad URL null
java.lang.RuntimeException: Bad URL null
at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:151)
at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:114)
Caused by: java.net.MalformedURLException
at java.net.URL.<init>(URL.java:154)
at java.net.URL.<init>(URL.java:127)
at com.android.volley.toolbox.HurlStack.performRequest(HurlStack.java:102)
at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:97)
at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:114)
public class AppController extends Application {
public static final String TAG = AppController.class
.getSimpleName();
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static AppController mInstance;
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
mImageLoader = new ImageLoader(this.mRequestQueue,
new BitmapCache());
}
return this.mImageLoader;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
public class MainActivity extends AppCompatActivity {
public final String URL = new String("http://api.androidhive.info/volley/person_object.json");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("VOLLEY", URL);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Method.POST, null, URL, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("VOLLEY", response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("VOLLEY", error.toString());
}
});
AppController.getInstance().addToRequestQueue(jsonObjectRequest, "JSON_OBJ");
}
}
я реализовал нечто подобное этому, и это относительно просто. Ваше сообщение журнала печатает то, что выглядит как тарабарщина, потому что
response.data
— это действительно массив байтов — неString
. Кроме того,VolleyError
это действительно лишь затянувшийсяException
, так что исключение.getMessage () скорее всего не вернет то, что вы ищете, если вы не переопределите методы разбора для разбора вашегоVolleyError
в расширенномRequest
класса. Очень простой способ справиться с этим будет делать что-то вроде://In your extended request class @Override protected VolleyError parseNetworkError(VolleyError volleyError){ if(volleyError.networkResponse != null && volleyError.networkResponse.data != null){ VolleyError error = new VolleyError(new String(volleyError.networkResponse.data)); volleyError = error; } return volleyError; } }
если вы добавите это в свой расширенный
Request
классов,getMessage()
должны, по крайней мере, не возвращать null. Я обычно не очень беспокоюсь об этом, хотя, так как это достаточно легко сделать все это изнутри вашегоonErrorResponse(VolleyError e)
метод.вы должны использовать библиотеку JSON для упрощения вещей — я использую Gson например, или вы можете использовать Apache
JSONObject
s, которые не должны требовать дополнительной внешней библиотеки. Первый шаг состоит в том, чтобы получить ответ JSON отправляется с вашего сервера какString
(аналогично тому, что я только что продемонстрировал), далее вы можете дополнительно преобразовать его в JSONObject (используя либо apacheJSONObject
s иJsonArray
s, или другая библиотека по вашему выбору) или просто разобратьString
себя. После этого вам просто нужно отобразитьToast
.вот пример кода, чтобы вы начали:
public void onErrorResponse(VolleyError error) { String json = null; NetworkResponse response = error.networkResponse; if(response != null && response.data != null){ switch(response.statusCode){ case 400: json = new String(response.data); json = trimMessage(json, "message"); if(json != null) displayMessage(json); break; } //Additional cases } } public String trimMessage(String json, String key){ String trimmedString = null; try{ JSONObject obj = new JSONObject(json); trimmedString = obj.getString(key); } catch(JSONException e){ e.printStackTrace(); return null; } return trimmedString; } //Somewhere that has access to a context public void displayMessage(String toastString){ Toast.makeText(context, toastString, Toast.LENGTH_LONG).show(); }
Привет, ребята, может кто-нибудь помочь мне с этим классом? Я получаю сообщение об ошибке, и я новичок только в студии Android и мобильной разработке. Я учусь и получаю знания. Помогите, пожалуйста.
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Toast.makeText(Register.this, response, Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Register.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put(NAME, pangaran);
params.put(SURNAME, apelyido);
params.put(ADDRESS, lugar);
params.put(CONTACTNO, kontak);
params.put(USERNAME, username1);
params.put(PASSWORD, password1);
return params;
}
};
requestQueue.add(stringRequest);
3 ответа
См. эту ссылку, надеюсь, это поможет вам установить время для залпа.
И если это не поможет, просто дайте мне знать.
ОБНОВЛЕНО
В конце я вставил код, чтобы изменить время по умолчанию, установленное залпом, вы можете установить время самостоятельно, оно должно быть в миллисекундах.
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Toast.makeText(Register.this, response, Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Register.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put(NAME, pangaran);
params.put(SURNAME, apelyido);
params.put(ADDRESS, lugar);
params.put(CONTACTNO, kontak);
params.put(USERNAME, username1);
params.put(PASSWORD, password1);
return params;
}
};
//10000 is the time in milliseconds adn is equal to 10 sec
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
10000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(stringRequest);
1
Community
20 Июн 2020 в 12:12
Для меня: что только для вашего «VPN» отключите «VPN».
1
mohsen nejati
23 Янв 2020 в 15:30
Может быть, вы можете увеличить тайм-аут, чтобы проверить, все ли работает нормально. Поскольку вы сказали, что ваш код работал на вас ранее, возможная причина может заключаться в том, что вашему серверу потребовалось меньше времени, чтобы ответить на ваш запрос, что может быть не всегда одинаковым из-за трафика.
Попробуйте добавить следующие строки к существующему коду.
stringRequest.setRetryPolicy(new RetryPolicy() {
@Override
public int getCurrentTimeout() {
return 30000;
}
@Override
public int getCurrentRetryCount() {
return 30000;
}
@Override
public void retry(VolleyError error) throws VolleyError {
}
});
5
devgun
8 Дек 2017 в 08:02
0 / 0 / 0
Регистрация: 17.09.2021
Сообщений: 44
1
При запуске приложения на телефоне выдает ошибку
14.08.2022, 05:59. Показов 415. Ответов 3
Я установил open server вроде его настроил, зашел в phpmyadmin, создал бд и таблицу users.
android manifest
Код
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" package="com.example.registerlogindemo"> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <application android:allowBackup="true" android:dataExtractionRules="@xml/data_extraction_rules" android:fullBackupContent="@xml/backup_rules" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.RegisterLoginDemo" android:usesCleartextTraffic="true" android:networkSecurityConfig="@xml/network_security_config" tools:targetApi="31"> <activity android:name=".MainActivity" android:exported="true"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".success" android:exported="false" /> <activity android:name=".register" android:exported="false" /> </application> </manifest>
MainActivity.java
Код
[JAVA]package com.example.registerlogindemo; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import java.util.HashMap; import java.util.Map; public class MainActivity extends AppCompatActivity { private EditText etEmail, etPassword; private String email, password; private final String URL = "http://""/admin/login.php"; // Здесь "" ip моего пк @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); email = password = ""; etEmail = findViewById(R.id.etEmail); etPassword = findViewById(R.id.etPassword); } public void login(View view) { email = etEmail.getText().toString().trim(); password = etPassword.getText().toString().trim(); if(!email.equals("") && !password.equals("")){ StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, response -> { Log.d("res", response); if (response.equals("success")) { Intent intent = new Intent(MainActivity.this, success.class); startActivity(intent); finish(); } else if (response.equals("failure")) { Toast.makeText(MainActivity.this, "Invalid Login Id/Password", Toast.LENGTH_SHORT).show(); } }, error -> Toast.makeText(MainActivity.this, error.toString().trim(), Toast.LENGTH_SHORT).show()){ @Override protected Map<String, String> getParams() { Map<String, String> data = new HashMap<>(); data.put("email", email); data.put("password", password); return data; } }; RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext()); requestQueue.add(stringRequest); }else{ Toast.makeText(this, "Fields can not be empty!", Toast.LENGTH_SHORT).show(); } } public void register(View view) { Intent intent = new Intent(this, register.class); startActivity(intent); finish(); } } [/JAVA]
Java | ||
|
register.java
Код
[JAVA]package com.example.registerlogindemo; import android.app.Activity; import android.content.Intent; import android.os.Bundle; 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 com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import java.util.HashMap; import java.util.Map; public class register extends Activity { private EditText etName, etEmail, etPassword, etReenterPassword; private TextView tvStatus; private Button btnRegister; private final String URL = "http://""/admin/register.php"; private String name, email, password, reenterPassword; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_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, response -> { if (response.equals("success")) { tvStatus.setText("Successfully registered."); btnRegister.setClickable(false); } else if (response.equals("failure")) { tvStatus.setText("Something went wrong!"); } }, error -> Toast.makeText(getApplicationContext(), error.toString().trim(), Toast.LENGTH_SHORT).show()){ @Override protected Map<String, String> getParams() { 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(); } }[/JAVA]
__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь
0