为什么布局不显示?

时间:2014-12-13 13:34:29

标签: php android mysql json

我尝试从php解析到android使用json,我使用locallhost(xampp)。当我解析布局时只显示加载ascnytsk,我使用url 10.0.2.2:81但是当我使用url http://api.androidhive.info/json/movies.json布局时可以显示。 我编辑localhost成为127.0.0.1:81

这是主要活动

public class MainActivity extends ListActivity {

private ProgressDialog pDialog;
// ALL JSON node names
public static final String TAG_NAME = "nama";

public static final String URL_CATEGORY = "http://10.0.2.2:81/bantulfolder/lihatpantai.php";
// albums JSONArray
JSONArray categories = null;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
// private ListView lv;
private BaseAdapter mAdapter;
ArrayList<HashMap<String, String>> categoryList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    categoryList = new ArrayList<HashMap<String, String>>();
    Log.d("onCreate: ", "Yep");
    // get listview
    ListView lv = getListView();

    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View view, int position,
                long arg3) {
            // TODO Auto-generated method stub
            Toast.makeText(MainActivity.this, "Item selected: " + position,
                    Toast.LENGTH_LONG).show();


        }

    });
    new LoadCategories().execute(); 
}

class LoadCategories extends AsyncTask<String, String, String> {
    @Override
    protected void onPreExecute() {
    super.onPreExecute();
    pDialog = new ProgressDialog(MainActivity.this);
    //pDialog.setMessage("Listing Categories...");
    pDialog.setIndeterminate(false);
    pDialog.setCancelable(false);
    pDialog.show();
    }
    @Override
    protected String doInBackground(String... args) {
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    // getting JSON string from URL
    String json = jsonParser.makeHttpRequest(URL_CATEGORY, "GET",
    params);
    // Check your log cat for JSON reponse
    Log.d("Categories JSON: ", "> " + json);
    return json;
    }
    @Override
    protected void onPostExecute(String json) {
    try {
    categories = new JSONArray(json);
    if (categories != null) {
    // looping through All albums
    for (int i = 0; i < categories.length(); i++) {
    JSONObject c = categories.getJSONObject(i);
    // Storing each json item values in variable

    String name = c.getString(TAG_NAME);

// creating new HashMap
    HashMap<String, String> map = new HashMap<String, String>();
    // adding each child node to HashMap key => value
    map.put(TAG_NAME, name);

    // adding HashList to ArrayList
    categoryList.add(map);
    }
    mAdapter = new Adapter(MainActivity.this,
    categoryList);
    getListView().setAdapter(mAdapter);
    // dismiss the dialog after getting all albums
    pDialog.dismiss();
    } else {
    Log.d("Categories: ", "null");
    }
    } catch (JSONException e) {
    e.printStackTrace();
    }
    }
    }
}

这是适配器

 public class Adapter extends BaseAdapter {
private Context mContext;
LayoutInflater inflater;
private final ArrayList<HashMap<String, String>> urls;
HashMap<String, String> resultp = new HashMap<String, String>();
public Adapter(Context context,
ArrayList<HashMap<String, String>> items) {
mContext = context;
urls = items;
}
public int getCount() {
return urls.size();
}
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return getItem(position).hashCode();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView name, rating, genre, realase;
ImageView gambar;

inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.edit_layout, parent,
false);
resultp = urls.get(position);
name = (TextView) view.findViewById(R.id.judul);

name.setText(resultp.get(MainActivity.TAG_NAME));
return view;
}
}

这是json

public class JSONParser {
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {
    }

    /**
     * Making service call
     * 
     * @url - url to make request
     * @method - http request method
     * */
    public String makeHttpRequest(String url, String method) {
        return this.makeHttpRequest(url, method, null);
    }

    public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));
            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();
            Log.e("JSON", json);
        } 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;
    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public String makeHttpRequest(String url, String method,
            List<NameValuePair> params) {
        // Making HTTP request
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            // check for request method
            if (method == "POST") {
                HttpPost httpPost = new HttpPost(url);
                if (params != null) {
                    httpPost.setEntity(new UrlEncodedFormEntity(params));
                }
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            } else if (method == "GET") {
                if (params != null) {
                    String paramString = URLEncodedUtils
                            .format(params, "utf-8");
                    url += "?" + paramString;
                }
                HttpGet httpGet = new HttpGet(url);
                // DefaultHttpClient httpClient = new
                // DefaultHttpClient(httpParameters);
                HttpResponse httpResponse = httpClient.execute(httpGet);
                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());
        }
        // return JSON String
        return json;
    }
}
logchat中的

可以采用字符串但不能在布局中显示:(

{"catagories":[{"nama":"coba","alamat":"coba","gambar":"milanak.png","deskripsi":"Masukan deskripsi coba"}]}

0 个答案:

没有答案