dop20345 2017-04-05 11:28
浏览 198
已采纳

当响应只是表中的一行时,如何使用okhttp从json响应中获取java对象

I'm trying to get a java object 'Product' from json response, the json response returns only one row from the table, and I don't khnow if I have to use a JSONObject or a JSONArray or both, anyway I've tried both but it doesn't work it's giving me a NullPointerException. Here'e my code:

public class ConsultProductActivity extends AppCompatActivity {
    String idProduit;
    Product prod;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        Bundle extra = intent.getExtras();
        idProduit = extra.getString("idProduit");
        Toast.makeText(ConsultProductActivity.this, idProduit, Toast.LENGTH_SHORT).show();
        setContentView(R.layout.activity_consult_product);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_rest);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        prod = prepareFullInfo();
        getSupportActionBar().setTitle(prod.getName());
        ImageView imgAvant = (ImageView) findViewById(R.id.img_avant);
        Glide.with(ConsultProductActivity.this).load(prod.getImg_avant()).into(imgAvant);
        ImageView imgArriere = (ImageView) findViewById(R.id.img_arriere);
        Glide.with(ConsultProductActivity.this).load(prod.getImg_arriere()).into(imgArriere);
        ImageView imgCote = (ImageView) findViewById(R.id.img_cote);
        Glide.with(ConsultProductActivity.this).load(prod.getImg_coté()).into(imgCote);
        TextView prix = (TextView) findViewById(R.id.prix_consult_p);
        prix.setText(prod.getPrice());
        AppCompatTextView description = (AppCompatTextView) findViewById(R.id.description);
        description.setText(prod.getDescription());
    }

    public Product prepareFullInfo() {
        AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
            String productUrl = new String("http://moodyinformatics.000webhostapp.com/product_full_info.php?id=" + idProduit);


            @Override
            protected Void doInBackground(Void... params) {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder().url(productUrl).build();


                try {
                    Response response = client.newCall(request).execute();
                    JSONArray array = new JSONArray(response.body().string());
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject object = array.getJSONObject(i);
                        prod = new Product(object.getInt("id_produit"), object.getString("nom"), object.getString("description"), object.getInt("qte_stock"), object.getInt("prix"), object.getString("img_avant"), object.getString("img_arriere"), object.getString("img_cote"));
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            return  null;
            }

                @Override
            protected void onPostExecute(Void aVoid) {

            }
        };

        task.execute();
        return prod;
    }

My php file:

<?php 
header('Content-Type: application/json; Charset=UTF-8');
require "conn.php";
$id_produit=$_GET['id'];
$sql = "select p.id_produit, p.nom, p.description, p.prix, p.qte_stock, a.img_avant, a.img_arriere, a.img_cote from produit p, album_photos a where p.id_produit='".$id_produit."' and p.id_produit= a.id_produit";
$response = array();
$result = mysqli_query($conn, $sql); 
while ($row = mysqli_fetch_assoc($result)){
    $array[]= $row;
}
$jsn= json_encode($array, JSON_UNESCAPED_UNICODE);
$jsn1 = str_replace('\/', '/', $jsn);
$jsn1 = str_replace('
', ' ', $jsn1);
$jsn1= str_replace('images/', 'http://moodyinformatics.000webhostapp.com/images/', $jsn1);
echo $jsn1;
mysqli_close($conn);
 ?>

the response of the server when idProduit=12

[  
   {  
      "id_produit":"12",
      "nom":"Switch Ethernet TP-Link TL-SG105",
      "description":"10/100/1000 : 5 ports Gigabit Contrôle de flux 802.3x : 802.3x Gestion QoS (Quality of Service) 802.1P : 802.1p",
      "prix":"3900",
      "qte_stock":"5",
      "img_avant":"http://moodyinformatics.000webhostapp.com/images/12.2.jpg",
      "img_arriere":"http://moodyinformatics.000webhostapp.com/images/12.3.jpg",
      "img_cote":"http://moodyinformatics.000webhostapp.com/images/12.4.jpg"
   }
]
  • 写回答

1条回答 默认 最新

  • duanfa2014 2017-04-05 14:52
    关注

    AsyncTask works on a new thread to execute a particular task. Method prepareFullInfo returns immediately, while the task is already in execution. You have to get results in onPostExecute method.

    public class ConsultProductActivity extends AppCompatActivity {
    String idProduit;
    Product prod;
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        Bundle extra = intent.getExtras();
        idProduit = extra.getString("idProduit");
        Toast.makeText(ConsultProductActivity.this, idProduit, Toast.LENGTH_SHORT).show();
        setContentView(R.layout.activity_consult_product);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_rest);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        prepareFullInfo();
    }
    
    public void prepareFullInfo() {
        AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
            String productUrl = new String("http://moodyinformatics.000webhostapp.com/product_full_info.php?id=" + idProduit);
    
    
            @Override
            protected Void doInBackground(Void... params) {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder().url(productUrl).build();
    
    
                try {
                    Response response = client.newCall(request).execute();
                    JSONArray array = new JSONArray(response.body().string());
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject object = array.getJSONObject(i);
                        prod = new Product(object.getInt("id_produit"), object.getString("nom"), object.getString("description"), object.getInt("qte_stock"), object.getInt("prix"), object.getString("img_avant"), object.getString("img_arriere"), object.getString("img_cote"));
                    }
    
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            return  null;
            }
    
                @Override
            protected void onPostExecute(Void aVoid) {
                getSupportActionBar().setTitle(prod.getName());
                ImageView imgAvant = (ImageView) findViewById(R.id.img_avant);
                 Glide.with(ConsultProductActivity.this).load(prod.getImg_avant()).into(imgAvant);
                ImageView imgArriere = (ImageView) findViewById(R.id.img_arriere);
                Glide.with(ConsultProductActivity.this).load(prod.getImg_arriere()).into(imgArriere);
                ImageView imgCote = (ImageView) findViewById(R.id.img_cote);
                Glide.with(ConsultProductActivity.this).load(prod.getImg_coté()).into(imgCote);
                TextView prix = (TextView) findViewById(R.id.prix_consult_p);
                prix.setText(prod.getPrice());
                AppCompatTextView description = (AppCompatTextView) findViewById(R.id.description);
                description.setText(prod.getDescription());
            }
        };
    
        task.execute();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办