我有1个应用程序正在使用retrofit2将图片上传到000webhost服务器并且它可以工作。在此之前,我使用XAMPP将数据上传到数据库,现在我正在尝试将我在XAMPP上的所有工作转移到000webhost。
问题是当我尝试上传数据时收到错误消息,错误为could not invoke virtual method toString() on a null referance
。
除了URL之外,java代码是相同的并且php文件是相同的。
我认为存在问题,因为网站是安全的。另外使用retrofit2对我来说很难,因为我很难理解如何使用它,但我可以尝试一个好的指南。
不重复:我知道什么是nullPoint异常,问题是我不明白为什么我从服务器收到一个空值。该应用程序无法访问该PHP文件,因此它没有得到响应,我不明白如何解决它。
也是为什么一个应用程序可以访问但另一个不能访问。
create_product.php:
<?php
$response = array();
if (isset($_POST['name']) && isset($_POST['price']) && isset($_POST['description']))
{
$name = $_POST['name'];
$price = $_POST['price'];
$description = $_POST['description'];
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
$result = $db->query("INSERT INTO products(name, price, description) VALUES('$name', '$price', '$description')");
if ($result) {
$response["success"] = 1;
$response["message"] = "Product successfully created.";
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
echo json_encode($response);
}
} else {
$response["success"] = 0;
$response["message"] = "missing fields";
echo json_encode($response);
}
?>
JSONParser:
package com.example.user.onlineshop;
import android.content.ContentValues;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class JSONParser {
static JSONObject jObj;
static String json;
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public static JSONObject makeHttpRequest(String url, String method, ContentValues params) {
// Making HTTP request
try {
final OkHttpClient client = new OkHttpClient();
Request request;
// check for request method
if (method.equals("POST")) {
// request method is POST
MediaType contentType = MediaType.parse("application/x-www-form-urlencoded; charset=UTF-8");
String content = "";
for (String key : params.keySet())
{
if ( !content.isEmpty())
content += "&";
content += key + "=" + params.get(key);
}
RequestBody body = RequestBody.create(contentType, content);
request = new Request.Builder().url(url).post(body).build();
}
else {
// request method is GET
request = new Request.Builder().url(url).build();
}
final Response response = client.newCall(request).execute();
json = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e ){
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
NewProductActivity:
package com.example.user.onlineshop;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import org.json.JSONException;
import org.json.JSONObject;
public class NewProductActivity extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputPrice;
EditText inputDesc;
ContentValues params;
String name;
String price;
String description;
// адрес для создания нового товара
IpAddressClass IAC= new IpAddressClass();
String ip=IAC.getIp();
private String url_create_product = "http://swane2.000webhostapp.com/PicUpload/create_product.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_product);
params = new ContentValues();
inputName = (EditText) findViewById(R.id.inputName);
inputPrice = (EditText) findViewById(R.id.inputPrice);
inputDesc = (EditText) findViewById(R.id.inputDesc);
Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);
btnCreateProduct.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// создаем новый товар в другом потоке
name = inputName.getText().toString();
price = inputPrice.getText().toString();
description = inputDesc.getText().toString();
new CreateNewProductTask().execute();
}
});
}
// Фоновая задача для создания нового товара
class CreateNewProductTask extends AsyncTask<String, String, String> {
// Сначала запустим окно с индикатором прогресса
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewProductActivity.this);
pDialog.setMessage("Creating product");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
}
// Создаем товар
protected String doInBackground(String... args) {
// Подготавливаем параметры
params.put("name", name);
params.put("price",price);
params.put("description", description);
// получаем объект JSON через POST
JSONObject json = jsonParser.makeHttpRequest(url_create_product,"POST", params);
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// при успешном создании товара
// запускаем активность всех товаров
Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
startActivity(i);
// закрываем экран активности
finish();
} else {
// не получилось создать товар
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// закрываем диалоговое окно с индикатором
}
}
}
编辑:在错误发生之前,我在logcat中收到此消息:
D/NetworkSecurityConfig: No Network Security Config specified, using platform default