JSON解析器无法运行

时间:2013-11-01 10:32:54

标签: java android json

我的应用程序无法从服务器读取数据,但我在代码或错误日志中找不到错误。事实上,在检查我的API后,链接工作正常。 INTERNET和WRITE_EXTERNAL_STORAGE权限已在清单中设置。

我的代码:

package com.berthojoris.bacaberita;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.berthojoris.bacaberita.adapter.BeritaAdapter;
import com.berthojoris.bacaberita.bean.BeritaBean;
import com.berthojoris.bacaberita.lib.Constants;
import com.berthojoris.bacaberita.lib.ImageLoader;
import com.berthojoris.bacaberita.lib.JSONParser;
import com.berthojoris.bacaberita.lib.Utils;
import com.berthojoris.bacaberita.sqlite.UtilBerita;

public class Berita extends ListActivity {

    ProgressDialog dialog;
    private static String urlBerita = "http://newapi.bacaberita.com/berita";
    public ImageLoader imageLoader;
    private JSONParser jParser;
    Toast msg;
    TextView notfound;
    JSONArray contacts = null;
    ArrayList<BeritaBean> AmbilDataBean = new ArrayList<BeritaBean>();
    BeritaAdapter adapter;
    UtilBerita UtilBerita;

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

        dialog = new ProgressDialog(this);
        UtilBerita = new UtilBerita(this);
        imageLoader = new ImageLoader(this.getApplicationContext());

        notfound = (TextView) findViewById(R.id.notfound);
        notfound.setVisibility(View.GONE);
        getListView().setVisibility(View.VISIBLE);

        AmbilDataBean = new ArrayList<BeritaBean>();
        adapter = new BeritaAdapter(this, AmbilDataBean);
        setListAdapter(adapter);

        Utils.setPolicyThread();

        // Creating JSON Parser Instance
        jParser = new JSONParser();
        Log.e("Berita Activity", "TOTAL SIZE DATABASE : "
                + UtilBerita.ReadBerita().size());

        if (UtilBerita.ReadBerita().size() < 1) {
            Log.e("Berita Activity", "DATABASE KOSONG. JALANKAN ASYNC");
            new async().execute();
        } else {
            AmbilDataBean = UtilBerita.ReadBerita();
            adapter.setItem(AmbilDataBean);
            Log.e("Berita Activity", "DATABASE DIAMBIL");
        }

        setTimerRefresh();

    }// Tutup onCreate

    private class async extends AsyncTask<Void, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            AmbilDataBean = new ArrayList<BeritaBean>();
            dialog.setMessage("Please wait...");
            dialog.setCanceledOnTouchOutside(false);
            dialog.show();
        }

        @Override
        protected String doInBackground(Void... params) {
            String jsonContent = jParser.getJSONDataFromUrl(urlBerita);
            Log.e("Berita Activity", "PROSES BACKGROUND DIJALANKAN");
            return jsonContent;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (result.length() > 0) {
                dialog.dismiss();

                // parsing disini
                JSONObject json = null;
                try {
                    json = new JSONObject(result);

                    try {
                        // Getting Array of Contacts
                        contacts = json.getJSONArray(Constants.TAG_ITEM);

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

                            // Storing each json item in variable
                            String id = c.getString(Constants.TAG_MenuID);
                            String judul = c.getString(Constants.TAG_Title);
                            //String img = c.getString(Constants.TAG_Link);
                            String desk = c.getString(Constants.TAG_Post);
                            String date = c.getString(Constants.TAG_Created);

                            BeritaBean mb = new BeritaBean();
                            mb.setID(id);
                            mb.setTitle(judul);
                            //mb.setLink("http://" + img);
                            mb.setPost(desk);
                            mb.setCreated(date);

                            AmbilDataBean.add(mb);

                        }

                        adapter.setItem(AmbilDataBean);
                        Log.e("Berita Activity",
                                "PROSES SELESAI. DATA AKAN DITAMPILKAN");

                    } catch (Exception e) {
                        dialog.dismiss();
                        Toast.makeText(getBaseContext(),
                                "Connection Error. Please try again...",
                                Toast.LENGTH_SHORT).show();
                    }

                    // selecting single ListView item
                    ListView lv = getListView();

                    // Launching new screen on Selecting Single ListItem
                    lv.setOnItemClickListener(new OnItemClickListener() {

                        @Override
                        public void onItemClick(AdapterView<?> parent,
                                View view, int position, long id) {

                        }
                    });

                } catch (Exception e) {
                    dialog.dismiss();
                    Toast.makeText(getBaseContext(),
                            "Connection Error. Please try again...",
                            Toast.LENGTH_SHORT).show();
                }

            } // Tutup if (result.length() > 0)
            else {
                dialog.dismiss();
                Toast.makeText(getBaseContext(),
                        "Data Not Found. Please try again...",
                        Toast.LENGTH_SHORT).show();
            }

            if (AmbilDataBean.size() < 1) {
                notfound.setVisibility(View.VISIBLE);
                getListView().setVisibility(View.GONE);
            } else {

                for (BeritaBean bean : AmbilDataBean) {
                    if (UtilBerita.getDetailWhereID(bean.getID()).getID() == null) {
                        Log.e("Berita Activity",
                                "Insert database : " + bean.getID());
                        UtilBerita.CreateData(bean);
                    } else {
                        Log.e("Berita Activity",
                                "Update database : " + bean.getID());
                        UtilBerita.UpdateBerita(bean);
                    }
                }

                notfound.setVisibility(View.GONE);
                getListView().setVisibility(View.VISIBLE);
            }
        } // Tutup onPostExecute
    } // Tutup private class async extends AsyncTask

    // =========================================================================================================================

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            new AlertDialog.Builder(this)
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .setMessage(R.string.really_quit)
                    .setPositiveButton(R.string.yes,
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog,
                                        int which) {
                                    finish();
                                }

                            }).setNegativeButton(R.string.no, null).show();

            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }

    }

    // =========================================================================================================================

    // Declare the timer
    Timer timer = null;
    final Handler handler = new Handler();

    public void setTimerRefresh() {

        timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {

            public void run() {

                handler.post(new Runnable() {
                    public void run() {
                        Log.e("Main Activity", "RUNNING TASK...");
                        new async().execute();
                    }
                });

            }

        }, 1000 * 60 * 1, 1000 * 25);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }

        if (UtilBerita != null)
            UtilBerita.Close();

    }

}

==更新==

我的常数类:

package com.berthojoris.bacaberita.lib;

public class Constants {
    public static final String TAG_ITEM = "items";

    public static final String TAG_MenuID = "Menu_ID";
    public static final String TAG_IsDisplay = "IsDisplay";
    public static final String TAG_CategoryName = "CategoryName";
    public static final String TAG_CategoryID = "Category_ID";
    public static final String TAG_ContentID = "Content_ID";
    public static final String TAG_Title = "Title";
    public static final String TAG_Post = "Post";
    public static final String TAG_Link = "Link";
    public static final String TAG_Meta = "Meta";
    public static final String TAG_CreatedBy = "CreatedBy";
    public static final String TAG_Created = "Created";
    public static final String TAG_StartDisplay = "StartDisplay";
    public static final String TAG_Counter = "counter";

}

1 个答案:

答案 0 :(得分:0)

您必须从jsonObject items检索jsonArray。但是在您的代码中,您没有在任何地方使用items。试试这个:

    String jsonStr = new ConnectionService().connectionGet("http://newapi.bacaberita.com/berita","");
    JSONObject jsonObject = new JSONObject(jsonStr);
    System.out.println("..........JSON OBJECT.............");
    System.out.println(jsonObject); // full json Object
    JSONArray jsonArray = jsonObject.getJSONArray("items");
    System.out.println("..........JSON ARRAY PARSING.............");
    for(int i=0;i<jsonArray.length();i++)
    {
        String menu_id = jsonArray.getJSONObject(i).getString("Menu_ID");
        String is_display = jsonArray.getJSONObject(i).getString("IsDisplay");
        System.out.println("MENU_ID: "+menu_id);
        System.out.println("IsDisplay: "+is_display);
    }

以上示例中使用的方法如下:

     public static String connectionGet(String url, String parameter) throws MalformedURLException, ProtocolException, IOException {

    URL url1 = new URL(url);
    HttpURLConnection request1 = (HttpURLConnection) url1.openConnection();
    request1.setRequestMethod("GET");
    request1.connect();
    String responseBody = convertStreamToString(request1.getInputStream());
    return responseBody;
}

private static String convertStreamToString(InputStream is) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line).append("\n");
        }
    } catch (IOException e) {
    } finally {
        try {
            is.close();
        } catch (IOException e) {
        }
    }

    return sb.toString();
}