【问题标题】:How to fetch data from mysql in android?如何从android中的mysql获取数据?
【发布时间】:2015-10-01 06:19:07
【问题描述】:

您好,我是 android 新手,我按照一些在线教程从 android 中的 mysql 获取数据。但是当我尝试获取数据时,我得到 json “No Value for : json Data”的异常。

    public class MainActivity extends ActionBarActivity {

    String myJSON;

    private static final String TAG_RESULTS="result";
    private static final String TAG_NAME = "message_recd";
    private static final String TAG_ADD ="message_sent";

    JSONArray peoples = null;

    ArrayList<HashMap<String, String>> personList;

    ListView list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        list = (ListView) findViewById(R.id.listView);
        personList = new ArrayList<HashMap<String,String>>();
        getData();
    }


    protected void showList(){
        try {
            JSONObject jsonObj = new JSONObject(myJSON);
            peoples = jsonObj.getJSONArray(TAG_RESULTS);
                for(int i=0;i<peoples.length();i++){
                JSONObject c = peoples.getJSONObject(i);
                String name=null, address=null;

                if(c.has("message_recd"))
                    name = c.getString("message_recd");
                else if(c.has("message_sent"))
                    address = c.getString("message_sent");

                HashMap<String,String> persons = new HashMap<String,String>();


                persons.put(TAG_NAME,name);
                persons.put(TAG_ADD,address);
                personList.add(persons);
            }

            ListAdapter adapter = new SimpleAdapter(
                    MainActivity.this, personList, R.layout.list_item,
                    new String[]{TAG_NAME,TAG_ADD},
                    new int[]{R.id.name, R.id.address}
            );

            list.setAdapter(adapter);

        } catch (JSONException e) {
            Log.i("tagconvertstr", "["+myJSON+"]");
        }
    }

    public void getData(){
        class GetDataJSON extends AsyncTask<String, Void, String>{

            @Override
            protected String doInBackground(String... params) {
                DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
                HttpPost httppost = new HttpPost("http://10.0.2.2/progress_card/messages/get_messages1.php");

                // Depends on your web service
                httppost.setHeader("Content-type", "application/json");

                InputStream inputStream = null;
                String result = null;
                try {
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity entity = response.getEntity();

                    inputStream = entity.getContent();
                    // json is UTF-8 by default
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                    StringBuilder sb = new StringBuilder();

                    String line = null;
                    while ((line = reader.readLine()) != null)
                    {
                        sb.append(line + "\n");
                    }
                    result = sb.toString();
                } catch (Exception e) {
                    // Oops
                }
                finally {
                    try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
                }
                return result;
            }

            @Override
            protected void onPostExecute(String result){
                myJSON=result;
                showList();
            }
        }
        GetDataJSON g = new GetDataJSON();
        g.execute();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Logcat:

    10-01 03:07:55.910: I/tagconvertstr(1953): [{"0":{"message_recd":"hello is it working really?"},"1":{"message_recd":"hello"},"2":{"message_recd":"checking"},"3":{"message_recd":"qwerty"},"4":{"message_recd":"qweqwdqdqd"},"5":{"message_recd":"ojhdsgwkjsbawdfvkjn"},"6":{"message_recd":"qwertyyt"},"7":{"message_recd":"qwertyytqwertyytqwertyytqwertyytqwertyytqwertyyt"},"8":{"message_sent":"hey whtas up"},"9":{"message_sent":"hey whtas up again"},"10":{"message_sent":"hey whtas up hey whtas up hey whtas up hey whtas up hey whtas up "}}
10-01 03:07:55.910: I/tagconvertstr(1953): ]

Json 响应:

{"0":{"message_recd":"hello is it working really?"},"1":{"message_recd":"hello"},"2":{"message_recd":"checking"},"3":{"message_recd":"qwerty"},"4":{"message_recd":"qweqwdqdqd"},"5":{"message_recd":"ojhdsgwkjsbawdfvkjn"},"6":{"message_recd":"qwertyyt"},"7":{"message_sent":"hey whtas up"},"8":{"message_sent":"hey whtas up again"}}

【问题讨论】:

  • 通过Android访问MySQL数据库,最好的方法是使用PHP访问数据库。接下来,您将能够使用 PHP 从查询结果中生成 JSON 字符串。
  • 发布您从服务器获得的整个 json 响应
  • 尝试在 AsyncTask 的“void onPostExecute(String result){}”方法中提取 JSON 值..

标签: android json android-json


【解决方案1】:

看看这就是你想要做的:- 在 post 执行你做:- myJSON=result;

现在myJson的json结构是:-{"0":{"message_recd":"hello is it working really?"},"1":{"message_recd":"hello"},"2":{"message_recd":"checking"},"3":{"message_recd":"qwerty"},"4":{"message_recd":"qweqwdqdqd"},"5":{"message_recd":"ojhdsgwkjsbawdfvkjn"},"6":{"message_recd":"qwertyyt"},"7":{"message_sent":"hey whtas up"},"8":{"message_sent":"hey whtas up again"}}

在 Json {} 中表示一个 Json 对象,而 [] 表示它的 Json 数组。现在在方法 showList() 中你可以这样做:-

JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray(TAG_RESULTS);

其中 TAG_RESULTS = "结果"

所以我要求 Json Object jsonObj 给我一个 Json 数组,其键是“结果”但没有,请参阅 Json 结构。实际上,该 Json 对象上没有数组,它有多个 Json 对象,键为 0,1,2,3...8。

所以要从 jsonObj 中获取所有 Json 对象,我们将像这样循环:-

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

JsonObject myJsonObject = jsonObj.getJsonObject(i);

//check if it has value for key and do something with value
if(myJsonObject.has("message_recd")) {

  String meesageRecieved = myJsonObject.getString("message_recd")

//Add it to the hash map
}

// do same if we have more keys like message_recd in json 
}

你从那个 url 得到的 Json 结构不是你想得到的,它没有结果数组。快乐的 android 编码:)

【讨论】:

  • 感谢您的简要解释,但我仍然没有得到 json 数据
  • 一旦我们的 JSON 结构更改为 [{"message_sent":"Hey There"},{"message_recd:"Cool!!"}],Rishabh 的代码将完美运行。不需要那些 0 ,1,2等
  • @DhirenKumawat hi dhiren..in 方法 showList 删除行 peoples = jsonObj.getJSONArray(TAG_RESULTS);并将其 for(int i=0;i
【解决方案2】:

您得到的响应不是 json 结构。它看起来很好

高级休息客户端

{"0":{"message_recd":"hello is it working really?"},"1":{"message_recd":"hello"},"2":{"message_recd":"checking"},"3":{"message_recd":"qwerty"},"4":{"message_recd":"qweqwdqdqd"},"5":{"message_recd":"ojhdsgwkjsbawdfvkjn"},"6":{"message_recd":"qwertyyt"},"7":{"message_sent":"hey whtas up"},"8":{"message_sent":"hey whtas up again"}}

但在 android json 中应该是这样的:

{"response":"success","data":[{"cityid":"5","citynm":"Hyderabad"}]}

【讨论】:

    猜你喜欢
    • 2012-11-20
    • 1970-01-01
    • 2015-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-15
    • 2012-12-15
    • 2020-03-26
    相关资源
    最近更新 更多