Android   发布时间:2022-04-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了java – 在Fragments中使用JSON时,应用程序在Android开发中没有响应大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

我在android中使用导航抽屉.我通过JSON从URL获取数据.当我在加载片段时运行应用程序时会出现错误

我的片段类是:

import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Fragment;
import android.os.bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


public class QMFragment extends Fragment {



public QMFragment(){}

    // url to make request
    private static String url = "http://localhost/app/qm_data.PHP";

    // JSON Node names
    private static final String TAG_QM = "qm";
    private static final String TAG_ID = "id";
    private static final String TAG_NAME = "name";
    private static final String TAG_URL = "url";

    // Hashmap for ListView
    ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();

    // JSONArray
    JSONArray qmArray = null;

    // CreaTing JSON Parser instance
    JSONParser jParser = new JSONParser();

    // getTing JSON String from URL
    JSONObject json = jParser.getJSONFromUrl(url);


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceStatE) {


        View rootView = inflater.inflate(R.layout.fragment_qm, container, falsE);


        getData(); 


        return rootView;
    }

    public void getData(){
        try {
            // GetTing Array
            qmArray = json.getJSONArray(tag_QM);

            // looping through All Data
            for(int i = 0; i < qmArray.length(); i++){
                JSONObject c = qmArray.getJSONObject(i);

                // Storing each json item in variable
                String id = c.getString(tag_ID);
                String name = c.getString(tag_Name);
                String url = c.getString(tag_URL);

             // creaTing new HashMap
                HashMap<String, String> map = new HashMap<String, String>();

                // adding each child node to HashMap key => value
                map.put(tag_ID, id);
                map.put(tag_NAME, Name);
                map.put(tag_URL, url);


                // adding HashList to ArrayList
                contactList.add(map);

            }
        } catch (JSONException E) {
            e.printStackTrace();
        }

    }

}

而我的JSONParser.java是:

import java.io.bufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.httpentity;
import org.apache.http.httpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.httpPost;
import org.apache.http.impl.client.DefaulthttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url) {

        // Making http request
        try {
            // defaulthttpClient
            DefaulthttpClient httpClient = new DefaulthttpClient();
            httpPost httpPost = new httpPost(url);

            httpResponse httpResponse = httpClient.execute(httpPost);
            httpentity httpentity = httpResponse.getEntity();
            is = httpentity.getContent();           

        } catch (UnsupportedEncodingException E) {
            e.printStackTrace();
        } catch (ClientProtocolException E) {
            e.printStackTrace();
        } catch (IOException E) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception E) {
            Log.e("Buffer Error", "Error ConverTing Result " + e.toString());
        }

        // 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;

    }
}

我的XML是:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://scheR_664_11845@as.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:BACkground="@color/bg" >

    <TextView
        android:id="@+id/txtLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="40dp"
        android:layout_marginTop="5dp"
        android:text="@String/head"
        android:textColor="@color/text_color"
        android:textSize="25sp" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="1px"
        android:layout_alignParentLeft="true"
        android:layouT_Below="@+id/txtLabel"
        android:layout_marginTop="5dp"
        android:BACkground="#CCCCCC" />

    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layouT_Below="@+id/txtLabel"
        android:layout_marginTop="10dp" >

        <RelativeLayout
            android:id="@+id/navigate_RLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/txtqmhead"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@String/qm_heading"
                android:textSize="25sp"
                android:textColor="@color/text_color" />
            <TextView
                android:id="@+id/txtqmsub"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@String/qm_chn"
                android:textSize="18sp"
                android:textColor="@color/text_color"
                android:layouT_Below="@+id/txtqmhead"
                android:layout_marginLeft="28dp" />

            <TableLayout
                android:id="@+id/tbl"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_alignParentright="true"
                android:layouT_Below="@+id/txtqmsub"
                android:layout_marginTop="20dp" >


             </TableLayout>

        </RelativeLayout>
    </ScrollView>

</RelativeLayout>

PHP文件是:

<?PHP
    header('Content-type: application/json');

    $server = "localhost";
    $username = "root";
    $password = "";
    $db = "test";


$con = MysqL_connect("localhost",$username,$password);
if (!$con)
  {
  die('Could not connect: ' . MysqL_error());
  }
MysqL_SELEct_db($db, $con);

$result = MysqL_query("SELECT * FROM example ORDER BY date DESC");

while($row = MysqL_fetch_assoc($result))
  {
        $output['qm'][]=$row;
  }

print(json_encode($output));

MysqL_close($con);


?>

LogCat:

12-24 10:19:54.322: E/AndroidRuntime(1700): FATAL EXCEPTION: main
12-24 10:19:54.322: E/AndroidRuntime(1700): android.os.networkonmainthreadException
12-24 10:19:54.322: E/AndroidRuntime(1700):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1084)
12-24 10:19:54.322: E/AndroidRuntime(1700):     at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
12-24 10:19:54.322: E/AndroidRuntime(1700):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
12-24 10:19:54.322: E/AndroidRuntime(1700):     at java.net.InetAddress.getAllByName(InetAddress.java:220)
12-24 10:19:54.322: E/AndroidRuntime(1700):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
12-24 10:19:54.322: E/AndroidRuntime(1700):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
12-24 10:19:54.322: E/AndroidRuntime(1700):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
12-24 10:19:54.322: E/AndroidRuntime(1700):     at org.apache.http.impl.client.DefaultrequestDirector.execute(DefaultrequestDirector.java:360)
12-24 10:19:54.322: E/AndroidRuntime(1700):     at org.apache.http.impl.client.AbstracthttpClient.execute(AbstracthttpClient.java:555)
12-24 10:19:54.322: E/AndroidRuntime(1700):     at org.apache.http.impl.client.AbstracthttpClient.execute(AbstracthttpClient.java:487)
12-24 10:19:54.322: E/AndroidRuntime(1700):     at org.apache.http.impl.client.AbstracthttpClient.execute(AbstracthttpClient.java:465)
12-24 10:19:54.322: E/AndroidRuntime(1700):     at com.qrodsintegrated.JSONParser.getJSONFromUrl(JSONParser.java:38)
12-24 10:19:54.322: E/AndroidRuntime(1700):     at com.qrodsintegrated.QMFragment.<init>(QMFragment.java:41)
12-24 10:19:54.322: E/AndroidRuntime(1700):     at com.qrodsintegrated.MainActivity.displayView(MainActivity.java:175)
12-24 10:19:54.322: E/AndroidRuntime(1700):     at com.qrodsintegrated.MainActivity.access$0(MainActivity.java:164)
12-24 10:19:54.322: E/AndroidRuntime(1700):     at com.qrodsintegrated.MainActivity$SlideMenuClicklistener.onItemClick(MainActivity.java:126)
12-24 10:19:54.322: E/AndroidRuntime(1700):     at android.widget.AdapterView.performItemClick(AdapterView.java:292)
12-24 10:19:54.322: E/AndroidRuntime(1700):     at android.widget.AbsListView.performItemClick(AbsListView.java:1058)
12-24 10:19:54.322: E/AndroidRuntime(1700):     at android.widget.AbsListView$PerformClick.run(AbsListView.java:2514)
12-24 10:19:54.322: E/AndroidRuntime(1700):     at android.widget.AbsListView$1.run(AbsListView.java:3168)
12-24 10:19:54.322: E/AndroidRuntime(1700):     at android.os.Handler.handleCallBACk(Handler.java:605)
12-24 10:19:54.322: E/AndroidRuntime(1700):     at android.os.Handler.dispatchmessage(Handler.java:92)
12-24 10:19:54.322: E/AndroidRuntime(1700):     at android.os.Looper.loop(Looper.java:137)
12-24 10:19:54.322: E/AndroidRuntime(1700):     at android.app.ActivityThread.main(ActivityThread.java:4340)
12-24 10:19:54.322: E/AndroidRuntime(1700):     at java.lang.reflect.Method.invokeNative(Native Method)
12-24 10:19:54.322: E/AndroidRuntime(1700):     at java.lang.reflect.Method.invoke(Method.java:511)
12-24 10:19:54.322: E/AndroidRuntime(1700):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
12-24 10:19:54.322: E/AndroidRuntime(1700):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
12-24 10:19:54.322: E/AndroidRuntime(1700):     at dalvik.system.NativeStart.main(Native Method)

解决方法:

你有

 JSONObject json = jParser.getJSONFromUrl(url);

在JSONParser中

 httpResponse httpResponse = httpClient.execute(httpPost);

在ui线程上运行NetworkRelated操作.

使用AsyncTask或Thread

http://developer.android.com/reference/android/os/AsyncTask.html

 new TheTask().execute(params);  

然后

class TheTask extends AsyncTask<Void,Void,Void>
{
    protected void doInBACkg@R_674_7060@Void... params)
    {
       // your http request
      return null;
    }
}

你可以使asynctask成为片段的内部类,并在onPostExecute中更新ui

编辑:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceStatE) {
    View rootView = inflater.inflate(R.layout.fragment_qm, container, falsE);
    new TheTask().execute(url);
    return rootView;
}

然后

 class TheTask extends AsyncTask<String,String,String>
{
    @override
    protected String doInBACkg@R_674_7060@String... params)
    {
        String _response =null;
        try {
        // defaulthttpClient
        DefaulthttpClient httpClient = new DefaulthttpClient();
        httpPost httpPost = new httpPost(params[0]);

        httpResponse httpResponse = httpClient.execute(httpPost);
        httpentity httpentity = httpResponse.getEntity();
         _response=EntityUtils.toString(httpentity);
        }catch(Exception E)
        {
           e.printStacktrace();
        } 
      return _response;
    }
    @Override
    protected void onPostExecute(String result) {
    // TODO Auto-generated method stub
    super.onPostExecute(result);
    Log.i(".......",result);

}

}

大佬总结

以上是大佬教程为你收集整理的java – 在Fragments中使用JSON时,应用程序在Android开发中没有响应全部内容,希望文章能够帮你解决java – 在Fragments中使用JSON时,应用程序在Android开发中没有响应所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: