dongshuofu0039 2017-04-24 10:53
浏览 71

无法连接到000webhost上的PHP文件

I got 1 app that is using retrofit2 to upload a picture to the 000webhost server and it works. Before that I used XAMPP to upload data to a database and now I am trying to move all of my work on XAMPP to 000webhost. The problem is that I get an error message when I try to upload data and the error is could not invoke virtual method toString() on a null referance. The java code is the same and the php files are the same ,except from the URL. I think there is a problem because the site is secured. Also using retrofit2 is difficult to me as I am having a hard time trying to understand how to use it but I can try with a good guide. Not Duplicate: I know what is a nullPoint Exception, the problem is that I do not understand why I receive a null value from the server. The app can't access the php file so it doesn't get a response and I do not understand how to fix it. Also why one app can access but the other can't.

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

    }
}
}

Edit: Before the error happens I get this message in the logcat:

D/NetworkSecurityConfig: No Network Security Config specified, using platform default

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 有赏,i卡绘世画不出
    • ¥15 如何用stata画出文献中常见的安慰剂检验图
    • ¥15 c语言链表结构体数据插入
    • ¥40 使用MATLAB解答线性代数问题
    • ¥15 COCOS的问题COCOS的问题
    • ¥15 FPGA-SRIO初始化失败
    • ¥15 MapReduce实现倒排索引失败
    • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
    • ¥15 找一位技术过硬的游戏pj程序员
    • ¥15 matlab生成电测深三层曲线模型代码