【问题标题】:how to get json code into my app如何将 json 代码放入我的应用程序
【发布时间】:2016-12-19 07:22:40
【问题描述】:

我正在处理 JSON 解析,在我的 TypeMenu java 文件中,我从服务器获得响应,当我单击列表视图中的项目时,我应该在列表视图的下一个活动中获得相关项目。该列表视图项也来自服务器。

这里我只想从选定的项目中获取项目,但我在下一个活动 SubMenu.java 中从数据库中获取所有项目。就像如果我选择披萨,那么在下一个活动中我应该只获取与披萨相关的项目这是我的 TypeMenu.java 文件。

package com.example.zeba.broccoli;

  import android.app.ProgressDialog;
  import android.content.Intent;
  import android.os.AsyncTask;
  import android.os.Bundle;
  import android.support.v7.app.AppCompatActivity;
  import android.support.v7.widget.Toolbar;
  import android.util.Log;
  import android.view.MenuItem;
  import android.view.View;
  import android.widget.AdapterView;
  import android.widget.ListAdapter;
  import android.widget.ListView;
  import android.widget.SimpleAdapter;
  import android.widget.TextView;
  import android.widget.Toast;

  import org.json.JSONArray;
  import org.json.JSONException;
  import org.json.JSONObject;

  import java.util.ArrayList;
  import java.util.HashMap;



 public class TypeMenu extends AppCompatActivity {

 private String TAG = TypeMenu.class.getSimpleName();
 String bid;

private ProgressDialog pDialog;
private ListView lv;
private static final String TAG_BID = "bid";

// URL to get contacts JSON
private static String url = "http://cloud.granddubai.com/brtemp/index.php";

ArrayList<HashMap<String, String>> contactList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_type_menu);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);




    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    contactList = new ArrayList<>();

    lv = (ListView) findViewById(R.id.list);

    new GetContacts().execute();


    // on seleting single product
    // launching Edit Product Screen
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            // getting values from selected ListItem

            HashMap<String, String> selected = contactList.get(position);
            String keyId = new ArrayList<>(selected.keySet()).get(0);
            String type_items  = selected.get(keyId);
            Intent in = new Intent(getApplicationContext(), SubMenu.class);
           //  sending pid to next activity
            in.putExtra(TAG_BID ,type_items );
            startActivityForResult(in, 100);
            Toast.makeText(getApplicationContext(),"Toast" +type_items ,Toast.LENGTH_LONG).show();
        }
    });













}

/**
 * Async task class to get json by making HTTP call
 */
private class GetContacts extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(TypeMenu.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();
       // Toast.makeText(getApplicationContext(),"Toast",Toast.LENGTH_LONG).show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        HttpHandler sh = new HttpHandler();

        // Making a request to url and getting response
     String jsonStr = sh.makeServiceCall(url);

        Log.e(TAG, "Response from url: " + jsonStr);





        if (jsonStr != null) {
            try {
                JSONArray jsonArry = new JSONArray(jsonStr);

                for (int i = 0; i < jsonArry.length(); i++)
                {

                    JSONObject c = jsonArry.getJSONObject(i);
                    String id = c.getString("id");
                    String type = c.getString("type");
                    HashMap<String, String> contact = new HashMap<>();

                   contact.put("id", id);
                    contact.put("type", type);
                    contactList.add(contact);


                }
            } catch (final JSONException e) {
                Log.e(TAG, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Json parsing error: " + e.getMessage(),
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }
        } else {
            Log.e(TAG, "Couldn't get json from server.");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Couldn't get json from server. Check LogCat for possible errors!",
                            Toast.LENGTH_LONG)
                            .show();
                }
            });

        }

           return null;
       }



        @Override
             protected void onPostExecute(Void result) {
              super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
               ListAdapter adapter = new SimpleAdapter(
                    TypeMenu.this, contactList,
                    R.layout.list_item, new String[]{ "type","id"},
                    new int[]{
                    R.id.type,R.id.id});

            lv.setAdapter(adapter);
        }

}
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                return true;
            default:
                return super.onOptionsItemSelected(item);
            }
          }
          }

这是我的 SubMenu.java 文件:

    package com.example.zeba.broccoli;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;



public class SubMenu  extends AppCompatActivity {

    private String TAG = SubMenu.class.getSimpleName();
    String type_items ;

    private ProgressDialog pDialog;
    private ListView lv;
    private static final String TAG_BID = "bid";

    // URL to get contacts JSON
    private static String url = "http://cloud.granddubai.com/broccoli/menu_typeitem.php";

    ArrayList<HashMap<String, String>> contactList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_type_menu);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        Intent i = getIntent();

        // getting product id (pid) from intent
        type_items = i.getStringExtra(TAG_BID);
        Toast.makeText(getApplicationContext(),"Toast 12" + type_items ,Toast.LENGTH_LONG).show();

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        contactList = new ArrayList<>();

        lv = (ListView) findViewById(R.id.list);

        new GetContacts().execute();


        // on seleting single product
        // launching Edit Product Screen
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                pDialog = new ProgressDialog(SubMenu.this);
                pDialog.setMessage("Loading book details.");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(true);
                pDialog.show();
                // getting values from selected ListItem

                HashMap<String, String> selected = contactList.get(position);
                String keyId = new ArrayList<>(selected.keySet()).get(0);
                String type_items = selected.get(keyId);
                //Intent in = new Intent(getApplicationContext(), SubMenu.class);
                // sending pid to next activity
                // in.putExtra(TAG_BID ,text);
                //startActivityForResult(in, 100);
                Toast.makeText(getApplicationContext(),"Toast" + type_items,Toast.LENGTH_LONG).show();
            }
        });













    }

    /**
     * Async task class to get json by making HTTP call
     */
    private class GetContacts extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(SubMenu.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();
            // Toast.makeText(getApplicationContext(),"Toast",Toast.LENGTH_LONG).show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url);

            Log.e(TAG, "Response from url: " + jsonStr);





            if (jsonStr != null) {
                try {
                    JSONArray jsonArry = new JSONArray(jsonStr);

                    for (int i = 0; i < jsonArry.length(); i++)
                    {

                        JSONObject c = jsonArry.getJSONObject(i);
                        String id = c.getString("id");
                        String name = c.getString("name");
                        HashMap<String, String> contact = new HashMap<>();

                        contact.put("id", id);
                        contact.put("name", name);
                        contactList.add(contact);


                    }
                } catch (final JSONException e) {
                    Log.e(TAG, "Json parsing error: " + e.getMessage());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "Json parsing error: " + e.getMessage(),
                                    Toast.LENGTH_LONG)
                                    .show();
                        }
                    });

                }
            } else {
                Log.e(TAG, "Couldn't get json from server.");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Couldn't get json from server. Check LogCat for possible errors!",
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(
                    SubMenu.this, contactList,
                    R.layout.list_item, new String[]{ "name","id"},
                    new int[]{
                            R.id.type});
            lv.setAdapter(adapter);
        }

    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}

这是我的 php 文件..

<?php 
include ('config.php');

if (isset($_GET["mid"])) 
{
    $type_items = $_GET['mid'];

$sql = mysqli_query($conn,"SELECT * FROM main_menu_items WHERE type_items = '".$type_items."'");                                                          
$arr = array();
$i=0;
while($result = mysqli_fetch_array($sql))
{
$arr[$i]['id']= $result['id'];
$arr[$i]['name']= $result['name'];
$i++;
}
}
echo json_encode($arr);

?>

当我在浏览器上使用 url 时,我没有得到任何东西,只有 null 被写入,如果我在设备上检查它,它会显示像这样的错误 “Json 解析错误:org.json.JSONObject$1 类型的值为 null 无法转换为 JsonArray”

【问题讨论】:

  • 你得到的是 jsonObject 而不是数组...
  • STILL..SAME 来自 url 的响应:{"result":[{"name":null}]} 12-19 11:31:54.836 6598-6858/com.example.zeba.broccoli E/SubMenu:Json 解析错误:org.json.JSONObject 类型的值 {"result":[{"name":null}]} 无法转换为 JSONArray
  • 在 php 代码中也应该用 JSonObject 代替数组。
  • 你可以编码吗
  • 我没有得到任何价值..如果你以正确的方式编码 php,那么它就完美了

标签: java android json listview


【解决方案1】:

不要做这种傻事

jsut 添加Json Libray 从http://www.java2s.com/Code/Jar/g/Downloadgson222jar.htm 下载 或者

dependencies {
  compile 'com.google.code.gson:gson:2.6.2'
} 

就这样吧 电影是 pojo 类的响应

Gson gson = new GsonBuilder().create();
Movie movie = gson.fromJson(response, Movie.class);

更多详情 -https://guides.codepath.com/android/Leveraging-the-Gson-Libraryhttps://stackoverflow.com/a/22754230/4741746https://stackoverflow.com/a/28392599/4741746

像这样创建类

public class Responce implements Serializable {

    @SerializedName("result")
    public ArrayList<Data>  result;

    public class Data implements Serializable {

    @SerializedName("name")
    public String  name;


    }
}

然后在响应中解析它(将这 3 行放在此行下方 String jsonStr = sh.makeServiceCall(url); 此行)

Gson gson = new GsonBuilder().create();
Responce mResponce = gson.fromJson(jsonStr , Responce .class);
String mName =mResponce.result.name;

【讨论】:

  • 我已经添加了依赖项,但是在我的应用程序中将你的代码编码在哪里......对不起......我是 json 新手
  • Response from url: {"result":[{"name":null}]} in your response name is null 在php端检查为什么它是null使用是(mResponce.result.name! =null )
  • 放回声($result['name']); $arr[$i]['name']= $result['name']; 下面的行检查是否有数据(在控制台中打印)如果没有检查查询如果没有检查值是否存在于数据库中如果没有在数据库中插入值
  • 放回声($result['name']);并检查是否打印在控制台中的数据
【解决方案2】:

像这样用 JSONObject 替换 JsonArray

    JSONObject jsonObj = new JSONObject(jsonStr);
    String id = jsonObj.getString("id");
    String name = jsonObj.getString("name");
    HashMap<String, String> contact = new HashMap<>();

    contact.put("id", id);
    contact.put("name", name);
    contactList.add(contact);

【讨论】:

  • 我认为prblm与php有关...因为它没有采用type_item
猜你喜欢
  • 2015-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-04
  • 2011-08-14
  • 1970-01-01
相关资源
最近更新 更多