无法从服务器获取数据? JSON解析结果

时间:2015-10-16 03:31:29

标签: android json listview

我想从jsfiddle

解析JSON

我创建了这样的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"/>
</LinearLayout>

并创建了listview(row.xml),如下所示:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="6dip" >

<LinearLayout
    android:id="@+id/promotion_saja"
    android:layout_width="150dp"
    android:layout_height="160dp"
    android:orientation="vertical">
    <ImageView
        android:id="@+id/image_promotion"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/ic_launcher"/>
</LinearLayout>
<RelativeLayout
    android:id="@+id/detail_country"
    android:layout_width="match_parent"
    android:layout_height="160dp"
    android:layout_toRightOf="@+id/promotion_saja"
    android:layout_toEndOf="@+id/promotion_saja"
    android:orientation="vertical"
    android:layout_marginLeft="4dp">
    <TextView
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="TextView"
        android:textSize="24sp"
        android:textStyle="bold"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_marginBottom="4dp"/>

    <TextView
        android:id="@+id/description"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/name"
        android:layout_below="@+id/name"
        android:text="TextView"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_marginBottom="4dp"/>

    <TextView
        android:id="@+id/date_start"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/description"
        android:layout_below="@+id/description"
        android:text="TextView"
        android:textSize="14sp"
        android:textColor="@android:color/black"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_marginBottom="4dp"/>

    <TextView
        android:id="@+id/date_end"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/date_start"
        android:layout_below="@+id/date_start"
        android:text="TextView"
        android:textSize="14sp"
        android:textColor="@android:color/black"
        android:textAppearance="?android:attr/textAppearanceMedium"/>

</RelativeLayout>
</RelativeLayout>

之后我创建了这样的推广类:

public class Promotions {

private String name;
private String description;
private String date_start;
private String date_end;
private String image;

public Promotions() {
    // TODO Auto-generated constructor stub
}

public Promotions(String name, String description, String date_start, String date_end, String image) {
    super();
    this.name = name;
    this.description = description;
    this.date_start = date_start;
    this.date_end = date_end;
    this.image = image;
}


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 getDate_start() {
    return date_start;
}

public void setDate_start(String date_start) {
    this.date_start = date_start;
}

public String getDate_end() {
    return date_end;
}

public void setDate_end(String date_end) {
    this.date_end = date_end;
}

public String getImage() {
    return image;
}

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

然后我创建了这样的促销适配器:

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

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;

public class PromotionAdapter extends ArrayAdapter<Promotions> {
ArrayList<Promotions> promoList;
LayoutInflater vi;
int Resource;
ViewHolder holder;

public PromotionAdapter(Context context, int resource, ArrayList<Promotions> objects) {
    super(context, resource, objects);
    vi = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    Resource = resource;
    promoList = objects;
}


@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // convert view = design
    View v = convertView;
    if (v == null) {
        holder = new ViewHolder();
        v = vi.inflate(Resource, null);
        holder.imageview = (ImageView) v.findViewById(R.id.image_promotion);
        holder.Name = (TextView) v.findViewById(R.id.name);
        holder.Description = (TextView) v.findViewById(R.id.description);
        holder.Date_start = (TextView) v.findViewById(R.id.date_start);
        holder.Date_end = (TextView) v.findViewById(R.id.date_end);
        v.setTag(holder);
    } else {
        holder = (ViewHolder) v.getTag();
    }
    holder.imageview.setImageResource(R.drawable.ic_launcher);
    new DownloadImageTask(holder.imageview).execute(promoList.get(position).getImage());
    holder.Name.setText(promoList.get(position).getName());
    holder.Description.setText(promoList.get(position).getDescription());
    holder.Date_start.setText("Start: " + promoList.get(position).getDate_start());
    holder.Date_end.setText("End: " + promoList.get(position).getDate_end());
    return v;

}

static class ViewHolder {
    public ImageView imageview;
    public TextView Name;
    public TextView Description;
    public TextView Date_start;
    public TextView Date_end;
}

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);
    }

}
}

我在MainActivity中调用了适配器,如下所示:

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

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
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 android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class MainActivity extends Activity {

ArrayList<Promotions> promoList;

PromotionAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    promoList = new ArrayList<Promotions>();
    new JSONAsyncTask().execute("http://dev.onlinedominosid.com/newApi/Promotions?region=JKT");

    ListView listview = (ListView)findViewById(R.id.list);
    listview.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                long id) {
            // TODO Auto-generated method stub
            Toast.makeText(getApplicationContext(), promoList.get(position).getName(), Toast.LENGTH_LONG).show();
        }
    });
}


class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {

    ProgressDialog dialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog = new ProgressDialog(MainActivity.this);
        dialog.setMessage("Loading, please wait");
        dialog.setTitle("Connecting server");
        dialog.show();
        dialog.setCancelable(false);
    }

    @Override
    protected Boolean doInBackground(String... urls) {
        try {
            HttpGet httppost = new HttpGet(urls[0]);
            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse response = httpclient.execute(httppost);

            // StatusLine stat = response.getStatusLine();
            int status = response.getStatusLine().getStatusCode();

            if (status == 200) {
                HttpEntity entity = response.getEntity();
                String data = EntityUtils.toString(entity);

                JSONArray jsono = new JSONArray(data);

                for(int i=0;i<jsono.length();i++){
                    //HashMap<String, String> promo = new HashMap<String, String>();
                    JSONObject object = jsono.getJSONObject(i);
                    Promotions actor = new Promotions();

                    actor.setName(object.getString("value_name_en"));
                    actor.setDescription(object.getString("value_desc_en"));
                    actor.setDate_start(object.getString("value_date_start"));
                    actor.setDate_end(object.getString("value_date_end"));
                    actor.setImage(object.getString("value_thumb_en"));

                    promoList.add(actor);
                }
                return true;
            }
        } catch (ParseException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return false;
    }

    protected void onPostExecute(Boolean result) {
        dialog.cancel();
        if(result == false){
            Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
        }else{
            adapter = new PromotionAdapter(getApplicationContext(), R.layout.row, promoList);
            ListView listview = (ListView)findViewById(R.id.list);
            listview.setAdapter(adapter);
        }
    }
    }

但是得到“无法从服务器获取数据”,我的JSON解析有什么问题吗? 我该怎么做才能纠正这些代码(正确的代码)?

1 个答案:

答案 0 :(得分:0)

嗨,HttpGet等Android的变化有点...... 您可以使用此代码获取链接的Json响应。

public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    new JSONAsyncTask()
            .execute("http://dev.onlinedominosid.com/newApi/Promotions?region=JKT");
}

public class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
    ProgressDialog dialog;

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        dialog = new ProgressDialog(MainActivity.this);
        dialog.setMessage("Loading, please wait");
        dialog.setTitle("Connecting server");
        dialog.show();
        dialog.setCancelable(false);
    }

    @Override
    protected Boolean doInBackground(String... urls) {
        String result = "";
        // TODO Auto-generated method stub
        try {
            //New Code of Sun Microsystem for Parsing.
            HttpURLConnection httpConnection;
            URL url = new URL(urls[0]);
            httpConnection = (HttpURLConnection) url.openConnection();
            httpConnection.setRequestProperty("Accept", "application/json");
            httpConnection.setReadTimeout(15000);
            httpConnection.setConnectTimeout(15000);
            httpConnection.setRequestMethod("GET");
            httpConnection.setDoInput(true);

            // StatusLine stat = response.getStatusLine();
            int status = httpConnection.getResponseCode();

            if (status == 200) {
                InputStream iStream = httpConnection.getInputStream();
                InputStreamReader isReader = new InputStreamReader(iStream);
                BufferedReader br = new BufferedReader(isReader);
                String line;
                while ((line = br.readLine()) != null) {
                    result += line;
                }
                Log.e("Data", result);
                //Create JSON Array of your Response.
                JSONArray jsonArray = new JSONArray(result);
                //Convert into Object.Here 0 no object is define,you can 
                //use for loop for all.
                JSONObject json = jsonArray.getJSONObject(0);
                //Get data using Key Value.
                Log.e("ValueId", json.getString("value_id"));
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    protected void onPostExecute(Boolean result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        dialog.dismiss();
        if (result == false)
            Toast.makeText(getApplicationContext(),
                    "Unable to fetch data from server", Toast.LENGTH_LONG)
                    .show();
        }
    }
}

并且不要忘记在这里添加互联网许可

<uses-permission android:name="android.permission.INTERNET"/>