Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/272.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Can';t连接到WebHost上的PHP文件_Java_Php_Android - Fatal编程技术网

Java Can';t连接到WebHost上的PHP文件

Java Can';t连接到WebHost上的PHP文件,java,php,android,Java,Php,Android,我得到了一个应用程序,它正在使用改进版2将图片上传到000webhost服务器,并且可以正常工作。在此之前,我使用XAMPP将数据上传到数据库,现在我正尝试将我在XAMPP上的所有工作转移到WebHost。 问题是,当我尝试上载数据时,收到一条错误消息,错误是无法在空引用上调用虚拟方法toString()。 除了URL之外,java代码和php文件是相同的。 我认为有一个问题,因为该网站是安全的。另外,使用改型2对我来说很困难,因为我很难理解如何使用它,但我可以在一个好的指导下尝试。 不重复:我

我得到了一个应用程序,它正在使用改进版2将图片上传到000webhost服务器,并且可以正常工作。在此之前,我使用XAMPP将数据上传到数据库,现在我正尝试将我在XAMPP上的所有工作转移到WebHost。 问题是,当我尝试上载数据时,收到一条错误消息,错误是
无法在空引用上调用虚拟方法toString()。
除了URL之外,java代码和php文件是相同的。
我认为有一个问题,因为该网站是安全的。另外,使用改型2对我来说很困难,因为我很难理解如何使用它,但我可以在一个好的指导下尝试。
不重复:我知道什么是空点异常,问题是我不理解为什么我从服务器接收空值。该应用程序无法访问php文件,因此它没有得到响应,我不知道如何修复它。
还有为什么一个应用可以访问,而另一个不能

创建_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);

} 

?>
新产品活动:

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) {
        // закрываем диалоговое окно с индикатором

    }
}
}
package com.example.user.onlineshop;
导入android.app.Activity;
导入android.app.ProgressDialog;
导入android.content.ContentValues;
导入android.content.Intent;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.util.Log;
导入android.view.view;
导入android.widget.Button;
导入android.widget.EditText;
导入org.json.JSONException;
导入org.json.JSONObject;
公共类NewProductActivity扩展了活动{
//进度对话框
私人对话;
JSONParser JSONParser=新的JSONParser();
编辑文本输入名;
编辑文本输入价格;
编辑文本输入描述;
内容值参数;
字符串名;
串价;
字符串描述;
// адрес для создания нового товара
IpAddressClass IAC=新的IpAddressClass();
字符串ip=IAC.getIp();
私有字符串url_创建_产品=”http://swane2.000webhostapp.com/PicUpload/create_product.php";
//JSON节点名称
私有静态最终字符串标记_SUCCESS=“SUCCESS”;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u new\u product);
params=新的ContentValues();
inputName=(EditText)findViewById(R.id.inputName);
inputPrice=(EditText)findViewById(R.id.inputPrice);
inputDesc=(EditText)findViewById(R.id.inputDesc);
按钮btnCreateProduct=(按钮)findViewById(R.id.btnCreateProduct);
btnCreateProduct.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
// создаем новый товар в другом потоке
name=inputName.getText().toString();
price=inputPrice.getText().toString();
description=inputDesc.getText().toString();
新建CreateNewProductTask().execute();
}
});
}
// Фоновая задача для создания нового товара
类CreateNewProductTask扩展了AsyncTask{
// Сначала запустим окно с индикатором прогресса
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
pDialog=newprogressdialog(NewProductActivity.this);
pDialog.setMessage(“创建产品”);
pDialog.setUndeterminate(假);
pDialog.setCancelable(真);
}
// Создаем товар
受保护的字符串doInBackground(字符串…args){
// Подготавливаем параметры
参数put(“名称”,名称);
参数卖出价(“价格”,价格);
参数put(“说明”,说明);
//邮政编码
JSONObject json=jsonParser.makeHttpRequest(url\u create\u product,“POST”,params);
d(“创建响应”,json.toString());
//检查成功标签
试一试{
int success=json.getInt(TAG_success);
如果(成功==1){
// при успешном создании товара
// запускаем активность всех товаров
Intent i=新Intent(getApplicationContext(),AllProductsActivity.class);
星触觉(i);
// закрываем экран активности
完成();
}否则{
// не получилось создать товар
}
}捕获(JSONException e){
e、 printStackTrace();
}
返回null;
}
受保护的void onPostExecute(字符串文件\u url){
// закрываем диалоговое окно с индикатором
}
}
}
编辑:在错误发生之前,我在logcat中收到以下消息:


D/NetworkSecurityConfig:未指定网络安全配置,使用平台默认值

是否获得堆栈跟踪?我不确定,您的意思是消息发送的路径?JSONParser类的另一个受害者来自此站点,不幸的是被用作此处多个问题的答案,因此。。。显然
jObj=newjsonobject(json)
首先应该在
try
catch
内,然后您不应该在此处获得可能重复的@Selvin,因为它位于
try/catch
块内。我知道服务器返回空值,但我不明白为什么以及如何修复它,因为代码是相同的(ip was
http://10.0.0.10:8012/onlineshop/create_product.php
相反)但结果不同。你有Stacktrace吗?我不确定,你是说消息发送的路径吗?JSONParser类的另一个受害者来自这个站点,不幸的是,它被用来回答这里的多个问题,所以。。。显然
jObj=newjsonobject(json)首先应该在里面
try
catch
然后你不应该在这里得到NPE@Selvin的可能副本它在
try/catchpackage 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) {
        // закрываем диалоговое окно с индикатором

    }
}
}