Android执行完美,但不显示任何内容

时间:2014-09-19 21:44:17

标签: android json parsing

我试图在教程的帮助下解析一个json对象(这个包http://www.youtube.com/watch?v=0Lr37suTPpg)。我一步一步地按照说明操作,然后设法得到了工作的例子。但是当我修改示例以使用我自己的json对象时,虽然没有错误,但模拟器只显示空白屏幕。

请记住,我的json对象是匿名的(请参阅下面的链接),不像示例中的那个。我已经对代码做了一些修改,但我对它们并不十分肯定。无论如何,我还没有找到问题的原因,所以我想请求你的帮助。下面是我的代码(3个java文件和2个xml),下面是工作示例的代码(显然也是3个java和2个xml)。

Sights.java(a.k.a. MainActivity.java /这里也是json对象的链接)

package com.example.thodoras.jsontutorialtest;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListView;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;


public class Sights extends Activity {

 ListView list;
SightsAdapter adapter;
ArrayList<HelperSights> sightsList;

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

    list = (ListView) findViewById(R.id.list);
    sightsList = new ArrayList<HelperSights>();

    new SightsAsyncTask().execute("http://www.escapeguide.gr/en/rest/views/mobile_listings.json?display_id=sights_service");
}

public class SightsAsyncTask extends AsyncTask<String, Void, Boolean> {

    @Override
    protected Boolean doInBackground(String... params) {


        try {

            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(params[0]);
            HttpResponse response = client.execute(post);
            int status = response.getStatusLine().getStatusCode();
            if (status == 200) {

                HttpEntity entity = response.getEntity();
                String data = EntityUtils.toString(entity);
                JSONArray array = new JSONArray(data);

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

                    HelperSights sights = new HelperSights();

                    JSONObject obj = array.getJSONObject(i);


                    sights.setImage(obj.getString("cover image"));
                    sights.setTitle(obj.getString("title"));
                    sights.setLocation(obj.getString("location"));

                    sightsList.add(sights);
                }

                return true;
            }

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

        return false;
    }


    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);

        if (result == false) {
            //something
        } else {
            SightsAdapter adapter = new SightsAdapter(getApplicationContext(), R.layout.row, sightsList);
            list.setAdapter(adapter);
        }
    }

}

}

package com.example.thodoras.jsontutorialtest;

HelperSights.java(包含getter setters)

public class HelperSights {

private String image;
private String title;
private String location;

public HelperSights(){

}

public String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getLocation() {
    return location;
}

public void setLocation(String location) {
    this.location = location;
}
}

SightsAdapter.java

package com.example.thodoras.jsontutorialtest;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.InputStream;
import java.util.ArrayList;


public class SightsAdapter extends ArrayAdapter<HelperSights> {

ArrayList<HelperSights> ArrayListSights;
int Resource;
Context context;
LayoutInflater vi;

public SightsAdapter(Context context, int resource, ArrayList<HelperSights> objects) {
    super(context, resource, objects);

    ArrayListSights = objects;
    Resource = resource;
    this.context = context;
    vi = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    ViewHolder holder;

    if(convertView == null){
        convertView = vi.inflate(Resource, null);
        holder = new ViewHolder();
        holder.sImage = (ImageView)convertView.findViewById(R.id.sImage);
        holder.sTitle = (TextView)convertView.findViewById(R.id.sTitle);
        holder.sLocation = (TextView)convertView.findViewById(R.id.sLocation);

        convertView.setTag(holder);
    } else {
        holder = (ViewHolder)convertView.getTag();
    }

    new DownloadImageTask(holder.sImage)
    .execute(ArrayListSights.get(position).getImage());
    holder.sTitle.setText(ArrayListSights.get(position).getTitle());
    holder.sLocation.setText(ArrayListSights.get(position).getLocation());

    return convertView;

}

static class ViewHolder{

    public ImageView sImage;
    public TextView sTitle;
    public TextView sLocation;

}

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    ImageView bmImage;

    public DownloadImageTask(ImageView bmImage) {
        this.bmImage = bmImage;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon11 = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mIcon11;
    }

    protected void onPostExecute(Bitmap result) {
        bmImage.setImageBitmap(result);
    }

}
}

activity_sights.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"    android:background="#F1F1F1"
tools:context=".MainActivity" >

<ListView
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:listitem="@layout/row" >

</ListView>

</LinearLayout>

row.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:id="@+id/LinearLayout1"
android:layout_height="match_parent">

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <ImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:id="@+id/sImage"
        android:scaleType="fitXY"
        android:src="@drawable/ic_launcher"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/sTitle"
            android:text="Yo
            "/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/sLocation"
            android:text="Man"/>

        </LinearLayout>


    </LinearLayout>

    </LinearLayout>

以下是可能有助于您比较的成功示例的文件。

MainActivity.java(包含json对象的链接)

package com.example.thodoras.jsontutorail;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListView;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;


public class MainActivity extends Activity {

ListView list;
ActorsAdapter adapter;
ArrayList<Actors> actorsList;

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

    list = (ListView) findViewById(R.id.list);
    actorsList = new ArrayList<Actors>();

    new    ActorAsyncTask()
.execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
}

public class ActorAsyncTask extends AsyncTask<String, Void, Boolean>{

    @Override
    protected Boolean doInBackground(String... params) {


        try {
            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(params[0]);
            HttpResponse response = client.execute(post);
            int status = response.getStatusLine().getStatusCode();
            if (status == 200) {
                HttpEntity entity = response.getEntity();
                String data = EntityUtils.toString(entity);
                JSONObject jObj = new JSONObject(data);
                JSONArray jArray = jObj.getJSONArray("actors");

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

                    Actors actor = new Actors();

                    JSONObject jRealObject = jArray.getJSONObject(i);

                    actor.setName(jRealObject.getString("name"));
                    actor.setDescription(jRealObject.getString("description"));
                    actor.setDob(jRealObject.getString("dob"));
                    actor.setCountry(jRealObject.getString("country"));
                    actor.setHeight(jRealObject.getString("height"));
                    actor.setSpouse(jRealObject.getString("spouse"));
                    actor.setChildren(jRealObject.getString("children"));
                    actor.setImage(jRealObject.getString("image"));

                    actorsList.add(actor);

                }

                return true;
            }

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

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);

        if(result == false){
            finish();
        } else {
            ActorsAdapter adapter = new ActorsAdapter
            (getApplicationContext(),R.layout.row, actorsList);
            list.setAdapter(adapter);
        }
    }
}
}

Actors.java(类似于HelperSights.java)

package com.example.thodoras.jsontutorail;



public class Actors {

private String name;
private String description;
private String dob;
private String country;
private String height;
private String spouse;
private String children;
private String image;

public Actors(){

}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public String getDob() {
    return dob;
}

public void setDob(String dob) {
    this.dob = dob;
}

public String getCountry() {
    return country;
}

public void setCountry(String country) {
    this.country = country;
}

public String getHeight() {
    return height;
}

public void setHeight(String height) {
    this.height = height;
}

public String getSpouse() {
    return spouse;
}

public void setSpouse(String spouse) {
    this.spouse = spouse;
}

public String getChildren() {
    return children;
}

public void setChildren(String children) {
    this.children = children;
}

public String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
}
}

ActorsAdapter.java

package com.example.thodoras.jsontutorail;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.InputStream;
import java.util.ArrayList;


public class ActorsAdapter extends ArrayAdapter<Actors> {

ArrayList<Actors> ArrayListActors;
int Resource;
Context context;
LayoutInflater vi;

public ActorsAdapter(Context context, int resource, ArrayList<Actors> objects) {
    super(context, resource, objects);

    ArrayListActors = objects;
    Resource = resource;
    this.context = context;

    vi = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);

}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    ViewHolder holder;

    if(convertView == null) {
        convertView = vi.inflate(Resource, null);
        holder = new ViewHolder();
        holder.tvName = (TextView)convertView.findViewById(R.id.tvName);
        holder.tvDescription = (TextView)convertView.findViewById(R.id.tvDescriptionn);
        holder.tvDob = (TextView)convertView.findViewById(R.id.tvDateOfBirth);
        holder.tvCountry = (TextView)convertView.findViewById(R.id.tvCountry);
        holder.tvHeight = (TextView)convertView.findViewById(R.id.tvHeight);
        holder.tvSpouse = (TextView)convertView.findViewById(R.id.tvSpouse);
        holder.tvChildren = (TextView)convertView.findViewById(R.id.tvChildren);
        holder.imageView = (ImageView)convertView.findViewById(R.id.ivImage);

        convertView.setTag(holder);
    }

    else {
        holder = (ViewHolder)convertView.getTag();
    }

    new DownloadImageTask(holder.imageView)
    .execute(ArrayListActors.get(position).getImage());
    holder.tvName.setText(ArrayListActors.get(position).getName());
    holder.tvDescription.setText(ArrayListActors.get(position).getDescription());
    holder.tvDob.setText(ArrayListActors.get(position).getDob());
    holder.tvCountry.setText(ArrayListActors.get(position).getCountry());
    holder.tvHeight.setText(ArrayListActors.get(position).getHeight());
    holder.tvSpouse.setText(ArrayListActors.get(position).getSpouse());
    holder.tvChildren.setText(ArrayListActors.get(position).getChildren());

    return convertView;
}

static class ViewHolder{

    public TextView tvName;
    public TextView tvDescription;
    public TextView tvDob;
    public TextView tvCountry;
    public TextView tvHeight;
    public TextView tvSpouse;
    public TextView tvChildren;
    public ImageView imageView;
}

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    ImageView bmImage;

    public DownloadImageTask(ImageView bmImage) {
        this.bmImage = bmImage;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon11 = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mIcon11;
    }

    protected void onPostExecute(Bitmap result) {
        bmImage.setImageBitmap(result);
    }

}
}

activity_main.xml中

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"    android:background="#F1F1F1"
tools:context=".MainActivity" >

<ListView
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:listitem="@layout/row" >

</ListView>

</LinearLayout>

行XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="4dp"
android:orientation="vertical" >

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <ImageView
        android:id="@+id/ivImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:src="@drawable/ic_launcher" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/tvName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Tom Cruise"
            android:textColor="#166CED"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <TextView
            android:id="@+id/tvDateOfBirth"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#D64530"
            android:text="Date of Birth: July 3, 1962" />

        <TextView
            android:id="@+id/tvHeight"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Height: 1.80 m"
            android:textColor="#D64530"
            android:textAppearance="?android:attr/textAppearanceSmall" />

        <TextView
            android:id="@+id/tvCountry"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#D64530"
            android:text="United States" />

    </LinearLayout>

</LinearLayout>

<TextView
    android:id="@+id/tvDescriptionn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="#009A57"
    android:text="Description" />

<TextView
    android:id="@+id/tvSpouse"
    android:layout_width="wrap_content" android:textColor="#166CED"
    android:layout_height="wrap_content"
    android:text="Spouse: Katie Holmes" />

<TextView
    android:id="@+id/tvChildren"
    android:layout_width="wrap_content" android:textColor="#166CED"
    android:layout_height="wrap_content"
    android:text="Children: Suri Cruise, Isabella Jane Cruise, Connor Cruise" />

</LinearLayout>

1 个答案:

答案 0 :(得分:0)

在原始示例中,Web服务以不同的方式构建。

您应该在HttpGet中使用SightsAsyncTask向服务器请求数据。

此外,我建议您使用HttpUrlConnection代替DefaultHttpClient。 获取数据的请求如下:

URL url = new URL("http://www.escapeguide.gr/en/rest/views/mobile_listings.json?display_id=sights_service");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
int status = connection.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
    InputStream is = new BufferedInputStream(connection.getInputStream());
    ByteArrayBuffer buffer = new ByteArrayBuffer(4096);
    int byteCount = 0;
    byte[] bytes = new byte[4096];
    do buffer.append(bytes, 0, byteCount); while ((byteCount = is.read(bytes)) != -1);
}
JSONArray array = new JSONArray(new String(buffer));

注意:上面的实现将输入流读取到字节数组。但是,您可以将其读取到String或StringBuilder,因为服务器响应的ContentType是文本(JSON)。读取到字节数组可以用作以不同格式(如PDF文件)返回数据的请求的通用解决方案