Last Updated
Viewed 184 Times
        

My application cannot read data from a server, but I can't find the error in my code or its error log. In fact, after checking my API, the link works fine. INTERNET and WRITE_EXTERNAL_STORAGE permission are already set in the manifest.

My code:

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

    }

}

== UPDATE ==

My Constants class :

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

}

In this for loop, my code looks for "name", "count", and "id", but sometimes the "count" object is not available in the JSON response. How can I set conditions when the "count" object is not present?

for(int i = 0; i < jArray.length(); i++){
    JSONObject albumData = jArray.getJSONObject(i);
    Global.albumArray.add(albumData.getString("name"));
        if (albumData.getString("count")==null){
            Global.countArray.add("?");
        }
        else{
            Global.countArray.add(albumData.getString("count"));
        }
    Global.linkArray.add(albumData.getString("id"));
}

The "if" statement doesn't work, obviously, but it is an example of what I'm trying to accomplish.

i am new to programming and I am making a json parser, but my thread method is not accessible, how do I go about doing this. When I debug, it goes into my getjson method but then skips the run method. I searched on stack over flow already but I am very confused about threading is there any good way to do this?

public class jsonParser {
 static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    // constructor
    public jsonParser() {

    }

    public JSONObject getJSONFromUrl(final String url) {

         Thread t = new Thread() {

public  void run() {
Looper.prepare(); //For Preparing Message Pool for the child Thread
       // 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) {
                // TODO Auto-generated catch block
Log.e("JSON Parser", "Error parsing data " + e.toString());     
                 }
            Looper.loop(); 
       return;     
      }
}; t.start();
return jObj;      
         }
                }

I am using the json google library. we can have this:

Public Class JsonParsing<T> {   

     private Gson gson;

     public JsonParsing(GsonBuilder builder) {
         this.gson = builder.create();
     }

     public T[] fromJsonFromArray(String json, Class<T[]> classOfT) {
         return gson.fromJson(json, classOfT);
     }
}

How we can create the instance of Class<T[]> in order to pass to this method?

Addenda:

I tried to create a generic method :

    public <T> T[] fromJsonFromArray(String json) {
        final Type type = new TypeToken<T[]>(){}.getType();
        return gson.fromJson(json, classOfT);
    }

It seems that I can not have a T[] as return. Then how can I parse an array of data with json format? Note: It is possible to do it in a non-generic way. Couldn't we have any generic solution?

Similar Question 4 (2 solutions) : JSON Parser error

Similar Question 5 (3 solutions) : Building a JSON search parser

Similar Question 6 (1 solutions) : Android json parser crashing

Similar Question 7 (3 solutions) : JSON parser for Java online

Similar Question 8 (2 solutions) : JSON parser crashes with objects

Similar Question 9 (3 solutions) : Android JSON parser Array

cc