Donate. I desperately need donations to survive due to my health

Get paid by answering surveys Click here

Click here to donate

Remote/Work from Home jobs

Navigation Drawer not showing in pages other than fragments

I am working on a project where I have used Navigation Drawer. The Navigation Drawer is working fine on main activity and in fragments. But I have to parse data from a JSON string and show it in a ListView when I do, it works but the navigation drawer disappears from this.I want the navigation drawer to be display in each activity. In this 1st image It is fine and I want each activity to be display like this

enter image description here

Now in this second image I parse the JSON string and show the data in ListView but it do not display Navigation Drawer which I need to display like in above image. how to attach the Navigation Drawer in this list and also everywhere in the app.

enter image description here

all the code I have written:

MianActivity.java

package com.example.webmaster.sbbwu;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

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

@Override
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;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_news) {
        getSupportFragmentManager().beginTransaction().replace(R.id.main_content, new NewsFragment()).commit();
    } else if (id == R.id.nav_events) {
        getSupportFragmentManager().beginTransaction().replace(R.id.main_content, new EventsFragment()).commit();
    } else if (id == R.id.nav_result) {
        getSupportFragmentManager().beginTransaction().replace(R.id.main_content, new ResultFragment()).commit();
    } else if (id == R.id.nav_career) {
        getSupportFragmentManager().beginTransaction().replace(R.id.main_content, new CareerFragment()).commit();
    } else if (id == R.id.nav_departments) {
        getSupportFragmentManager().beginTransaction().replace(R.id.main_content, new DepartmentsFragment()).commit();
    } else if (id == R.id.nav_contact) {
        getSupportFragmentManager().beginTransaction().replace(R.id.main_content, new ContactUsFragment()).commit();
    } else if (id == R.id.nav_share) {

    } else if (id == R.id.nav_send) {

    }
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}
}

DepartmentsFragments.java

package com.example.webmaster.sbbwu;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class DepartmentsFragment extends Fragment {
private BackegroundTask bTask;
public String json_string;
public View v;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    v = inflater.inflate(R.layout.fragment_departments,container,false);
    return v;
}


@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
    bTask = new BackegroundTask();
    bTask.execute();

}

class BackegroundTask extends AsyncTask<Void,Void,String> {
    String json_url;
    String JSON_STRING;
    @Override
    protected void onPreExecute() {
        json_url="http://sbbwu.edu.pk/sbbwu/Android/departments";

    }

    @Override
    protected String doInBackground(Void... voids) {
        try {
            URL url = new URL(json_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder stringBuilder = new StringBuilder();
            while((JSON_STRING = bufferedReader.readLine()) != null){

                stringBuilder.append(JSON_STRING+"\n");
            }

            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return stringBuilder.toString().trim();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }


    @Override
    protected void onPostExecute(String result) {
        json_string = result;
//            textView.setText(result);

        // for parsing
        Intent intentJsonDisplay = new         Intent(getActivity(),JsonListDisplay.class);
        intentJsonDisplay.putExtra("json_data",json_string);
        startActivity(intentJsonDisplay);

    }


}
}

JsonListDisplay.java

package com.example.webmaster.sbbwu;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class JsonListDisplay extends AppCompatActivity {

String json_string;
JSONObject jsonObject;
JSONArray jsonArray;
DeptAdapter deptAdapter;
ListView listView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_departments);
    listView = (ListView) findViewById(R.id.listView);

    deptAdapter = new DeptAdapter(this,R.layout.json_row_layout);
    listView.setAdapter(deptAdapter);
    json_string = getIntent().getExtras().getString("json_data");
    //create a row layout for elements of list
    try {
        jsonObject = new JSONObject(json_string);
        jsonArray = jsonObject.getJSONArray("server_reponse");
        int count = 0;
        String dept_name,dept_id;
        while(count<jsonArray.length()){
            JSONObject jo = jsonArray.getJSONObject(count);
            dept_name = jo.getString("dept_name");
            dept_id = jo.getString("dept_id");
            Dept dept = new Dept(dept_name,dept_id);
            deptAdapter.add(dept);
            count++;
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }


}
}

DeptAdapter.java

package com.example.webmaster.sbbwu;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;

public class DeptAdapter extends ArrayAdapter {

ArrayList list = new ArrayList<>();
public DeptAdapter(Context context, int resource) {
    super(context, resource);
}



public void add(Dept object) {
//        super.add(object);
    list.add(object);
}

@Override
public int getCount() {
    return list.size();
}


@Override
public Object getItem(int position) {
    return list.get(position);
}


@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View  row;
    row = convertView;
    DeptHolder deptHolder = new DeptHolder();
    if(row == null){
        LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        row = layoutInflater.inflate(R.layout.json_row_layout,parent,false);
//            DeptHolder deptHolder = new DeptHolder();
        deptHolder.txt_dept_name = row.findViewById(R.id.txt_dept);
        row.setTag(deptHolder);
    }else{
        deptHolder = (DeptHolder)row.getTag();
    }

    Dept dept = (Dept) this.getItem(position);
    deptHolder.txt_dept_name.setText(dept.getDept_name());

    return row;
}

static class DeptHolder {
    TextView txt_dept_name, txt_dept_id;

}
}

Dept.java

package com.example.webmaster.sbbwu;

public class Dept {

private String dept_name,dept_id;

public Dept(String dept_name, String dept_id) {
    this.setDept_name(dept_name);
    this.setDept_id(dept_id);
}

public String getDept_name() {
    return dept_name;
}

public void setDept_name(String dept_name) {
    this.dept_name = dept_name;
}

public String getDept_id() {
    return dept_id;
}

public void setDept_id(String dept_id) {
    this.dept_id = dept_id;
}
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">

<include
    layout="@layout/app_bar_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_main"
    app:menu="@menu/activity_main_drawer" />

</android.support.v4.widget.DrawerLayout>

app_bar_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorAccent"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_main" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/fab_margin"
    app:srcCompat="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

content_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context=".MainActivity"
tools:showIn="@layout/app_bar_main"
android:id="@+id/main_content">

</android.support.constraint.ConstraintLayout>

fagment_departments.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">


<ListView
    android:id="@+id/listView"
    android:layout_width="368dp"
    android:layout_height="495dp"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="8dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />


</android.support.constraint.ConstraintLayout>

json_row_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="60dp">

<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/txt_dept"
    android:text="Computer Science"
    android:gravity="center"
    android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"/>

</android.support.constraint.ConstraintLayout>

Comments