Ramesh Bista Ramesh Bista - 29 days ago 7
Android Question

Transition from list to new activity based on id(position)

I have class named school which contains a custom list of school which I pulled it form an api using volley library.On clicking to list items I want to move another activity(SchoolDetails) based on id(position).For example when I clicked list Item at id 1,I should be able to navigate to next activity with details of corresponding school. Here is my School.java

package com.example.user.educationhunt;

import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.example.user.educationhunt.adapter.CustomListAdapter;
import com.example.user.educationhunt.fragment.About;
import com.example.user.educationhunt.pojos.AppController;
import com.example.user.educationhunt.pojos.OurSchool;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class School extends AppCompatActivity{

// Log tag
private static final String TAG = School.class.getSimpleName();

// Billionaires json url
private static final String url = "http://myeducationhunt.com/public/schools";

private ProgressDialog pDialog;
private List<OurSchool> ourSchoolsListItems = new ArrayList<OurSchool>();
private ListView listView;
private CustomListAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_school);

ActionBar actionBar=getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle("Schools");


listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, ourSchoolsListItems);
listView.setAdapter(adapter);

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent=new Intent(School.this,SchoolDetails.class);
Bundle bundle = new Bundle();
bundle.putSerializable("id", ourSchoolsListItems.get(position));
intent.putExtras(bundle);
bundle.putInt("id",ourSchoolsListItems.get(position).schoolId);
bundle.putString("name",ourSchoolsListItems.get(position).schoolName);
bundle.putString("location",ourSchoolsListItems.get(position).schoolLocation);
bundle.putString("email",ourSchoolsListItems.get(position).schoolEmail);
bundle.putString("created_at",ourSchoolsListItems.get(position).createdAt);
bundle.putString("updated_at",ourSchoolsListItems.get(position).updatedAt);
bundle.putString("website",ourSchoolsListItems.get(position).schoolWebsite);

About about=new About();
about.setArguments(bundle);
startActivity(intent);
}
});

pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading…");
pDialog.show();

// Creating volley request obj
JsonArrayRequest billionaireReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();

// Parsing json
for (int i = 0; i < response.length(); i++) {
try {

JSONObject obj = response.getJSONObject(i);
OurSchool ourSchool = new OurSchool();
ourSchool.setSchoolName(obj.getString("name"));
ourSchool.setSchoolLogo(obj.getString("logo"));
ourSchool.setSchoolLocation(obj.getString("location"));
ourSchool.setSchoolEmail(obj.getString("email"));
ourSchool.setSchoolWebsite(obj.getString("website"));
ourSchool.setCreatedAt(obj.getString("created_at"));
ourSchool.setUpdatedAt(obj.getString("updated_at"));
// adding schools to ourSchool list
ourSchoolsListItems.add(ourSchool);

} catch (JSONException e) {
e.printStackTrace();
}
}

adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});

// Adding request to request queue
AppController.getInstance().addToRequestQueue(billionaireReq);
}

@Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}

private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
case R.id.schoolSearch:
default:
return super.onOptionsItemSelected(item);
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.search, menu);
return true;
}
}


This is my SchoolDetails.java.Please note that inside schooldetails activity I have used swipe tabs.

package com.example.user.educationhunt;

import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;

import com.example.user.educationhunt.fragment.About;
import com.example.user.educationhunt.fragment.Admission;
import com.example.user.educationhunt.fragment.FeeStructure;
import com.example.user.educationhunt.fragment.Majors;
import com.example.user.educationhunt.pojos.OurSchool;

import java.util.ArrayList;
import java.util.List;

public class SchoolDetails extends AppCompatActivity{

private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_school_details);

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

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);

tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);

OurSchool ourSchool= (OurSchool) getIntent().getExtras().get("id");


}

private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new About(), "ABOUT US");
adapter.addFragment(new Admission(), "ADMISSION");
// adapter.addFragment(new Majors(), "MAJORS");
adapter.addFragment(new FeeStructure(), "FEE");
viewPager.setAdapter(adapter);
}

class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();

public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}

@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}

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

public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}

@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}


Here goes my OurSchool

package com.example.user.educationhunt.pojos;

import java.io.Serializable;

/**
* Created by user on 11/3/2016.
*/
public class OurSchool implements Serializable {

public String schoolName;
private String schoolLogo;
public int schoolId;
public String schoolLocation;
public String createdAt;
public String updatedAt;
public String schoolEmail;
public String schoolWebsite;

public String getSchoolWebsite() {
return schoolWebsite;
}

public void setSchoolWebsite(String schoolWebsite) {
this.schoolWebsite = schoolWebsite;
}

public String getSchoolEmail() {
return schoolEmail;
}

public void setSchoolEmail(String schoolEmail) {
this.schoolEmail = schoolEmail;
}

public String getCreatedAt() {
return createdAt;
}

public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}

public String getUpdatedAt() {
return updatedAt;
}

public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}

public int getSchoolId() {
return schoolId;
}

public int setSchoolId(int schoolId) {
this.schoolId = schoolId;
return schoolId;
}

public String getSchoolName() {
return schoolName;
}

public void setSchoolName(String schoolName) {
this.schoolName = schoolName;
}

public String getSchoolLogo() {
return schoolLogo;
}

public void setSchoolLogo(String schoolLogo) {
this.schoolLogo = schoolLogo;
}

public String getSchoolLocation() {
return schoolLocation;
}

public void setSchoolLocation(String schoolLocation) {
this.schoolLocation = schoolLocation;
}

}


And this is my about.java Fragment

package com.example.user.educationhunt.fragment;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.user.educationhunt.R;
import com.example.user.educationhunt.pojos.OurSchool;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

/**
* A simple {@link Fragment} subclass.
*/
public class About extends Fragment implements OnMapReadyCallback{

MapView mapView;
GoogleMap map;
TextView aboutSchoolName,aboutSchoolLocation,aboutSchoolNumber,aboutSchoolEmail,aboutSchoolWebsite,aboutSchoolCategory;


public About() {
// Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_about, container, false);

aboutSchoolName= (TextView) v.findViewById(R.id.about_school_name);
aboutSchoolLocation= (TextView) v.findViewById(R.id.about_school_location);
aboutSchoolNumber= (TextView) v.findViewById(R.id.about_school_number);
aboutSchoolCategory= (TextView) v.findViewById(R.id.about_school_category);
aboutSchoolEmail= (TextView) v.findViewById(R.id.about_school_email);
aboutSchoolWebsite= (TextView) v.findViewById(R.id.about_school_website);

// String name=getArguments().getString("name");
// String location=getArguments().getString("location");
// String email=getArguments().getString("email");
// String website=getArguments().getString("website");
// String created=getArguments().getString("created");
// String updated=getArguments().getString("updated");

// aboutSchoolName.setText(name);
// aboutSchoolName.setText(location);
// aboutSchoolName.setText(email);
// aboutSchoolName.setText(website);
// aboutSchoolName.setText(created);
// aboutSchoolName.setText(updated);

// Gets the MapView from the XML layout and creates it
mapView = (MapView) v.findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);

// Gets to GoogleMap from the MapView and does initialization stuff
map = mapView.getMap();
map.getUiSettings().setMyLocationButtonEnabled(false);
map.setMyLocationEnabled(true);

// Needs to call MapsInitializer before doing any CameraUpdateFactory calls
MapsInitializer.initialize(this.getActivity());

// Updates the location and zoom of the MapView
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(27.6933, 85.3211), 15);
map.animateCamera(cameraUpdate);
onMapReady(map);

return v;
}

@Override
public void onResume() {
mapView.onResume();
super.onResume();
}

@Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}

@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}

@Override
public void onMapReady(GoogleMap map) {
map.addMarker(new MarkerOptions()
.position(new LatLng(27.6933, 85.3211))
.title("St. Xavier's College"));
}
}

Answer
  1. Implement Serializable in OurSchool class.

  2. Get OurSchool from list when item is clicked.

  3. Pass that object using intent to SchoolDetails class.

  4. Get the object in SchoolDetails class and use it.

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
          Intent intent=new Intent(School.this,SchoolDetails.class);
          Bundle bundle = new Bundle();
          bundle.putSerializable("key", ourSchoolsListItems.get(position));
          intent.putExtras(bundle);
          //start activity using startActivity() or startActivityForResult()
    }
    

In SchoolDetails activity add:

 OurSchool ourSchool = getIntent().getExtras().get("key");