App force close without internet JSON

im making an app using json on first activity but when the app is open without internet conection the app make a “force close”, i dont know what have to do to ovoid this error, help, im new on android and java

public class MainActivity extends ActionBarActivity {

String TITLES[] = {"Que es CMX","Ejecutivos(as)","Nuestros Servicios","Soluciones a tu Medida","Certificaciones Vigentes", "Cursos Online", "", "", "", ""};

int ICONS[] = {R.mipmap.organization,R.mipmap.conference,R.mipmap.services,R.mipmap.approval,R.mipmap.diploma1,R.mipmap.donate,R.id.linea,R.id.linea,R.id.linea,R.mipmap.home};

String NAME = "John Doe";
String EMAIL = "johndoe@cmx.org.mx";
int PROFILE = R.drawable.profile1;

private Toolbar toolbar;                              // Declaring the Toolbar Object

RecyclerView mRecyclerView;                           // Declaring RecyclerView
RecyclerView.Adapter mAdapter;                        // Declaring Adapter For Recycler View
RecyclerView.LayoutManager mLayoutManager;            // Declaring Layout Manager as a linear layout manager
DrawerLayout Drawer;                                  // Declaring DrawerLayout

ActionBarDrawerToggle mDrawerToggle;                  // Declaring Action Bar Drawer Toggle
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String RANK = "title";
static String COUNTRY = "place";
static String POPULATION = "date";
static String CONTENT1 = "content1";
static String CONTENT2 = "content2";
static String FLAG = "imagen";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Get the view from listview_main.xml
    setContentView(R.layout.listview_main);
    // Execute DownloadJSON AsyncTask
    new DownloadJSON().execute();

    toolbar = (Toolbar) findViewById(R.id.tool_bar);
    setSupportActionBar(toolbar);

    setTitle(R.string.title_activity_main);



    mRecyclerView = (RecyclerView) findViewById(R.id.RecyclerView); // Assigning the RecyclerView Object to the xml View

    mRecyclerView.setHasFixedSize(true);                            // Letting the system know that the list objects are of fixed size

    mAdapter = new MyAdapter(TITLES,ICONS,NAME,EMAIL,PROFILE,this);       // Creating the Adapter of MyAdapter class(which we are going to see in a bit)
    // And passing the titles,icons,header view name, header view email,
    // and header view profile picture

    mRecyclerView.setAdapter(mAdapter);                              // Setting the adapter to RecyclerView

    final GestureDetector mGestureDetector = new GestureDetector(MainActivity.this, new GestureDetector.SimpleOnGestureListener() {

        @Override public boolean onSingleTapUp(MotionEvent e) {
            return true;
        }

    });


    mRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
        @Override
        public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
            View child = recyclerView.findChildViewUnder(motionEvent.getX(),motionEvent.getY());



            if(child !=null && mGestureDetector.onTouchEvent(motionEvent)){
                Drawer.closeDrawers();

                if (recyclerView.getChildPosition(child) == 0) {
                    Intent intent = new Intent(MainActivity.this, Profile.class);
                    startActivity(intent);
                    finish();
                }else if
                        (recyclerView.getChildPosition(child) == 1) {
                    Intent intent = new Intent(MainActivity.this, CMX.class);
                    startActivity(intent);
                    finish();
                }else if
                        (recyclerView.getChildPosition(child) == 2) {
                    Intent intent = new Intent(MainActivity.this, Ejecutivos.class);
                    startActivity(intent);
                    finish();
                }else if
                        (recyclerView.getChildPosition(child) == 3){
                    Intent intent = new Intent(MainActivity.this, Servicios.class);
                    startActivity(intent);
                    finish();
                }else if
                        (recyclerView.getChildPosition(child) == 4){
                    Intent intent = new Intent(MainActivity.this, Soluciones.class);
                    startActivity(intent);
                    finish();
                }else if
                        (recyclerView.getChildPosition(child) == 5) {
                    Intent intent = new Intent(MainActivity.this, Certificaciones.class);
                    startActivity(intent);
                    finish();
                }else if
                        (recyclerView.getChildPosition(child) == 6){
                    Intent intent = new Intent(MainActivity.this, Web.class);
                    startActivity(intent);
                    finish();
                }else if
                        (recyclerView.getChildPosition(child) == 8 ){
                    Intent intent = new Intent(MainActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                }

                return true;

            }

            return false;
        }

        @Override
        public void onTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {

        }
    });


    mLayoutManager = new LinearLayoutManager(this);                 // Creating a layout Manager

    mRecyclerView.setLayoutManager(mLayoutManager);                 // Setting the layout Manager


    Drawer = (DrawerLayout) findViewById(R.id.DrawerLayout);        // Drawer object Assigned to the view
    mDrawerToggle = new ActionBarDrawerToggle(this,Drawer,toolbar,R.string.openDrawer,R.string.closeDrawer){

        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            // code here will execute once the drawer is opened( As I dont want anything happened whe drawer is
            // open I am not going to put anything here)
        }

        @Override
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
            // Code here will execute once drawer is closed
        }



    }; // Drawer Toggle Object Made
    Drawer.setDrawerListener(mDrawerToggle); // Drawer Listener set to the Drawer toggle
    mDrawerToggle.syncState();               // Finally we set the drawer toggle sync State
}

// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Create a progressdialog
        mProgressDialog = new ProgressDialog(MainActivity.this);
        // Set progressdialog message
        mProgressDialog.setMessage("Cargando...");
        mProgressDialog.setIndeterminate(false);
        // Show progressdialog
        mProgressDialog.show();
    }


    @Override
    protected Void doInBackground(Void... params) {
        // Create an array
        arraylist = new ArrayList<HashMap<String, String>>();
        // Retrieve JSON Objects from the given URL address
        jsonobject = JSONfunctions.getJSONfromURL("https://cmx.org.mx/wp-content/uploads/json.txt");

        try {
            // Locate the array name in JSON
            jsonarray = jsonobject.getJSONArray("posts");

            for (int i = 0; i < jsonarray.length(); i++) {
                HashMap<String, String> map = new HashMap<String, String>();
                jsonobject = jsonarray.getJSONObject(i);
                // Retrive JSON Objects
                map.put("title", jsonobject.getString("title"));
                map.put("place", jsonobject.getString("place"));
                map.put("date", jsonobject.getString("date"));
                map.put("content1", jsonobject.getString("content1"));
                map.put("content2", jsonobject.getString("content2"));
                map.put("imagen", jsonobject.getString("imagen"));
                // Set the JSON Objects into the array
                arraylist.add(map);
            }
        } catch (JSONException e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void args) {
        // Locate the listview in listview_main.xml
        listview = (ListView) findViewById(R.id.listview);
        // Pass the results into ListViewAdapter.java
        adapter = new ListViewAdapter(MainActivity.this, arraylist);
        // Set the adapter to the ListView
        listview.setAdapter(adapter);
        // Close the progressdialog
        mProgressDialog.dismiss();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    if (mDrawerToggle.onOptionsItemSelected(item)) {
        return true;
    }

    switch (item.getItemId()) {
        // Respond to the action bar's Up/Home button
        case R.id.about:

            Intent intent = new Intent(MainActivity.this, About.class);
            startActivity(intent);

            return true;
    }
    return super.onOptionsItemSelected(item);
}

}

public class JSONfunctions {

public static JSONObject getJSONfromURL(String url) {
    InputStream is = null;
    String result = "";
    JSONObject jArray = null;

    // Download JSON data from URL
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection " + e.toString());
    }

    // Convert response to string
    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();
        result = sb.toString();
    } catch (Exception e) {
        Log.e("log_tag", "Error converting result " + e.toString());
    }

    try {

        jArray = new JSONObject(result);
    } catch (JSONException e) {
        Log.e("log_tag", "Error parsing data " + e.toString());
    }

    return jArray;
}

}


Source: json

Leave a Reply