The code is working fine when testing in emulator-Android 7.1, API 25 but when I test same code in Real Device-Android 4.4.4, API 19 spinner is not showing. And there is no error message even
Config.java
public class Config {
public static String mLocation ="http://towncitycards.com/webservice_action.php?action=";
//http://towncitycards.com/webservice_action.php?action=filter_location
public static final String DATA_URL = mLocation+"filter_location";
//Tags used in the JSON String
public static final String TAG_USERNAME = "name";
public static final String TAG_NAME = "slug";
public static final String TAG_COURSE = "name";
public static final String TAG_SESSION = "slug";
//JSON array name
public static final String JSON_ARRAY = "location";
}
DemoSpinner.java
public class DemoSpinner extends AppCompatActivity implements Spinner.OnItemSelectedListener{
//Declaring an Spinner
private Spinner spinner;
//An ArrayList for Spinner Items
private ArrayList<String> students;
//JSON Array
private JSONArray result;
//TextViews to display details
private TextView textViewName;
private TextView textViewCourse;
private TextView textViewSession;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo);
//Initializing the ArrayList
students = new ArrayList<String>();
//Initializing Spinner
spinner = (Spinner) findViewById(R.id.spinner);
//Adding an Item Selected Listener to our Spinner
//As we have implemented the class Spinner.OnItemSelectedListener to this class iteself we are passing this to setOnItemSelectedListener
spinner.setOnItemSelectedListener(this);
//Initializing TextViews
textViewName = (TextView) findViewById(R.id.textViewName);
textViewCourse = (TextView) findViewById(R.id.textViewCourse);
textViewSession = (TextView) findViewById(R.id.textViewSession);
//This method will fetch the data from the URL
getData();
}
private void getData(){
//Creating a string request
StringRequest stringRequest = new StringRequest(Config.DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray(Config.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getStudents(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void getStudents(JSONArray j){
//Traversing through all the items in the json array
for(int i=0;i<j.length();i++){
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
//Adding the name of the student to array list
students.add(json.getString(Config.TAG_USERNAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, students));
}
//Method to get student name of a particular position
private String getName(int position){
String name="";
try {
//Getting object of given index
JSONObject json = result.getJSONObject(position);
//Fetching name from that object
name = json.getString(Config.TAG_NAME);
} catch (JSONException e) {
e.printStackTrace();
}
//Returning the name
return name;
}
//Doing the same with this method as we did with getName()
private String getCourse(int position){
String course="";
try {
JSONObject json = result.getJSONObject(position);
course = json.getString(Config.TAG_COURSE);
} catch (JSONException e) {
e.printStackTrace();
}
return course;
}
//Doing the same with this method as we did with getName()
private String getSession(int position){
String session="";
try {
JSONObject json = result.getJSONObject(position);
session = json.getString(Config.TAG_SESSION);
} catch (JSONException e) {
e.printStackTrace();
}
return session;
}
//this method will execute when we pic an item from the spinner
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//Setting the values to textviews for a selected item
textViewName.setText(getName(position));
textViewCourse.setText(getCourse(position));
textViewSession.setText(getSession(position));
}
//When no item is selected this method would execute
#Override
public void onNothingSelected(AdapterView<?> parent) {
textViewName.setText("");
textViewCourse.setText("");
textViewSession.setText("");
}
}
Please use this edited code this will work for you:
public class DemoSpinner extends AppCompatActivity implements Spinner.OnItemSelectedListener{
//Declaring an Spinner
private Spinner spinner;
//An ArrayList for Spinner Items
private ArrayList<String> students;
//JSON Array
private JSONArray result;
//TextViews to display details
private TextView textViewName;
private TextView textViewCourse;
private TextView textViewSession;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo);
//Initializing the ArrayList
students = new ArrayList<String>();
//Initializing Spinner
spinner = (Spinner) findViewById(R.id.spinner);
//Adding an Item Selected Listener to our Spinner
//As we have implemented the class Spinner.OnItemSelectedListener to this class iteself we are passing this to setOnItemSelectedListener
spinner.setOnItemSelectedListener(this);
//Initializing TextViews
textViewName = (TextView) findViewById(R.id.textViewName);
textViewCourse = (TextView) findViewById(R.id.textViewCourse);
textViewSession = (TextView) findViewById(R.id.textViewSession);
//This method will fetch the data from the URL
getData();
}
private void getData(){
//Creating a request queue
JsonObjectRequest StringRequest = new JsonObjectRequest(Request.Method.GET, Config.DATA_URL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if (response != null) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = response;
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray(Config.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getStudents(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("Volly error is this >>" + error);
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(StringRequest);
}
private void getStudents(JSONArray j){
//Traversing through all the items in the json array
for(int i=0;i<j.length();i++){
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
//Adding the name of the student to array list
students.add(json.getString(Config.TAG_USERNAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
Log.e("student >>",students.toString());
//Setting adapter to show the items in the spinner
spinner.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, students));
}
//Method to get student name of a particular position
private String getName(int position){
String name="";
try {
//Getting object of given index
JSONObject json = result.getJSONObject(position);
//Fetching name from that object
name = json.getString(Config.TAG_NAME);
} catch (JSONException e) {
e.printStackTrace();
}
//Returning the name
return name;
}
//Doing the same with this method as we did with getName()
private String getCourse(int position){
String course="";
try {
JSONObject json = result.getJSONObject(position);
course = json.getString(Config.TAG_COURSE);
} catch (JSONException e) {
e.printStackTrace();
}
return course;
}
//Doing the same with this method as we did with getName()
private String getSession(int position){
String session="";
try {
JSONObject json = result.getJSONObject(position);
session = json.getString(Config.TAG_SESSION);
} catch (JSONException e) {
e.printStackTrace();
}
return session;
}
//this method will execute when we pic an item from the spinner
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//Setting the values to textviews for a selected item
textViewName.setText(getName(position));
textViewCourse.setText(getCourse(position));
textViewSession.setText(getSession(position));
}
//When no item is selected this method would execute
#Override
public void onNothingSelected(AdapterView<?> parent) {
textViewName.setText("");
textViewCourse.setText("");
textViewSession.setText("");
}
}
StringRequest stringRequest = new StringRequest(Request. Method.GET,Config.DATA_URL, new Response.Listener()
Use it in getData(). Because you wasn't specified Request.Method.GET
::OR::
You can use same like this:
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("action", "filter_location");
return params;
}
};
Then remove the parameter "action=filter_location" from url.
Related
I'm trying is to display strings item_1 and item_2 in the text view 1 and text view 2 not displayed.
With the help of some experts I created the code below.
How can I display string item_1 and item_2 in the text view 1 and text view 2?
My Java code:
public class Prices extends AppCompatActivity {
TextView item_1 , item_2 ,a3 ,a4 ,a5 ,a6;
String url = "https://000000/app/almaraa/show.php";
RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prices);
TextView item_1 = (TextView) findViewById(R.id.item_1);
TextView item_2 = (TextView) findViewById(R.id.item_2);
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
final Globalv globalv = (Globalv) getApplicationContext();
try {
JSONArray jsonArray = response.getJSONArray("allmess");
for (int i = 0; i < response.length(); i++) {
JSONObject respons = jsonArray.getJSONObject(i);
String id = respons.getString("id");
String item_1 = respons.getString("item_1");
String item_2 = respons.getString("item_2");
}
JSONObject respons2 = jsonArray.getJSONObject(0);
String id = respons2.getString("id");
globalv.setTotal_threads(Integer.parseInt(String.valueOf(id)));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", "ERROR");
}
}
);
requestQueue.add(jsonObjectRequest);
}
}
You have to use the method setText(Charsequence) and run the code on UI thread.
But before, you have to rename Strings item_1 and item_2 because your TextViews have the same names. Below the code with String values renamed:
//......... inside your jsonObjectRequest
//rename item_1 and item_2
String myItem_1 = respons.getString("item_1");
String myItem_2 = respons.getString("item_2");
Prices.this.runOnUiThread(new Runnable() {
public void run() {
item_1.setText(myItem_1);
item_2.setText(myItem_2);
}
});
I want to change the sequence of my list view's items according to a specific input string which is matches with any of list view items contents and that item comes on the top of list view. I have tried hard but getting no success till now.if any other query please ask.
Here is the code for fetching data from server:
Here date2 is string input which I'm trying to compare
private void caladata() {
// showing refresh animation before making http call
swipeRefreshLayout.setRefreshing(false);
// Volley's json array request object
StringRequest stringRequest = new StringRequest(Request.Method.POST, CALENDAR_DATA,
new Response.Listener < String > () {
#Override
public void onResponse(String response) {
// Log.d(TAG, response.toString());
// hidePDialog();
JSONObject object = null;
try {
object = new JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
JSONArray jsonarray = null;
try {
jsonarray = object.getJSONArray("Table");
} catch (JSONException e) {
e.printStackTrace();
}
Calenndar_Model movie = new Calenndar_Model();
for (int i = 0; i < jsonarray.length(); i++) {
try {
JSONObject obj = jsonarray.getJSONObject(i);
movie.setUserid(obj.getString("userid"));
movie.setHost(obj.getString("eventname"));
String str = obj.getString("eventdate").replaceAll("\\D+","");
String upToNCharacters = str.substring(0, Math.min(str.length(), 13));
DateFormat timeZoneFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
timeZoneFormat.setTimeZone(TimeZone.getTimeZone("GMT-8"));
Date time = new Date(Long.parseLong(upToNCharacters));
// System.out.println(time);
movie.setDate(String.valueOf(timeZoneFormat.format(time)));
movie.setColor(obj.getString("eventcolor"));
movie.setAutoid(obj.getString("autoid"));
// Toast.makeText(getApplicationContext(), "server data respone", Toast.LENGTH_LONG).show();
int index=calList.indexOf(date2);
calList.add(movie);
calList.remove(date2);
calList.add(0, movie);
} catch (JSONException e) {
// Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
// listView.smoothScrollToPositionFromTop(selectedPos,0,300);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// VolleyLog.d(TAG, "Error: " + error.getMessage());
// hidePDialog();
}
}) {
#Override
protected Map < String, String > getParams() {
Map < String, String > params = new HashMap < String, String > ();
params.put("clientid", get1);
return params;
}
};
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(stringRequest);
}
Here is my adapter class:
public class CalendarListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Calenndar_Model> movieList;
public CalendarListAdapter(Activity activity, List<Calenndar_Model> movieList) {
this.activity = activity;
this.movieList = movieList;
}
public void swapList(List<Calenndar_Model> movieList) {
this.movieList = movieList;
notifyDataSetChanged();
}
#Override
public int getCount() {
return movieList.size();
}
#Override
public Object getItem(int location) {
return movieList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.calendar_listrow, null);
ImageView serial = (ImageView) convertView.findViewById(R.id.serial);
TextView title = (TextView) convertView.findViewById(R.id.title);
TextView date1 = (TextView) convertView.findViewById(R.id.date1);
title.setText(movieList.get(position).getHost());
date1.setText(movieList.get(position).getDate());
return convertView;
}
}
Model Class:
public class Calenndar_Model {
private String host, date,userid,color,autoid;
//private double rating;
public Calenndar_Model() {
}
public Calenndar_Model(String host,String date,String userid,String color,String autoid) {
this.host = host;
this.date = date;
this.userid = userid;
this.color = color;
this.autoid = autoid;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getAutoid() {
return autoid;
}
public void setAutoid(String autoid) {
this.autoid = autoid;
}
}
UPDATE: I found usage of date2 (the real name of variable, not data2 as you menthioned in description).
All you need is to sort your List<Calenndar_Model>:
private void caladata() {
// showing refresh animation before making http call
swipeRefreshLayout.setRefreshing(false);
// Volley's json array request object
StringRequest stringRequest = new StringRequest(Request.Method.POST, CALENDAR_DATA,
new Response.Listener < String > () {
#Override
public void onResponse(String response) {
// Log.d(TAG, response.toString());
// hidePDialog();
JSONObject object = null;
try {
object = new JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
JSONArray jsonarray = null;
try {
jsonarray = object.getJSONArray("Table");
} catch (JSONException e) {
e.printStackTrace();
}
calList = new ArrayList<>();
for (int i = 0; i < jsonarray.length(); i++) {
try {
JSONObject obj = jsonarray.getJSONObject(i);
Calenndar_Model movie = new Calenndar_Model();
movie.setUserid(obj.getString("userid"));
movie.setHost(obj.getString("eventname"));
String str = obj.getString("eventdate").replaceAll("\\D+","");
String upToNCharacters = str.substring(0, Math.min(str.length(), 13));
DateFormat timeZoneFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
timeZoneFormat.setTimeZone(TimeZone.getTimeZone("GMT-8"));
Date time = new Date(Long.parseLong(upToNCharacters));
//System.out.println(time);
movie.setDate(String.valueOf(timeZoneFormat.format(time)));
movie.setColor(obj.getString("eventcolor"));
movie.setAutoid(obj.getString("autoid"));
//Toast.makeText(getApplicationContext(), "server data respone", Toast.LENGTH_LONG).show();
calList.add(movie);
} catch (JSONException e) {
// Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
//sort calList list
Comparator<Calenndar_Model> calendarModelComparator = new Comparator<Calenndar_Model>() {
#Override
public int compare(Calenndar_Model cm1, Calenndar_Model cm2) {
boolean firstContainsData2 = calendarModelContainsData2(cm1);
boolean secondContainsData2 = calendarModelContainsData2(cm2);
if (firstContainsData2 && secondContainsData2) {
return 0;
} else if (firstContainsData2) {
return -1;
} else if (secondContainsData2) {
return 1;
} else return cm2.getData().compareTo(cm1.getData());
}
private boolean calendarModelContainsData2(Calenndar_Model cm) {
return cm.getData().contains(data2);
}
};
Collections.sort(calList, calendarModelComparator);
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.swapList(calList);
//listView.smoothScrollToPositionFromTop(selectedPos,0,300);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// VolleyLog.d(TAG, "Error: " + error.getMessage());
// hidePDialog();
}
}) {
#Override
protected Map < String, String > getParams() {
Map < String, String > params = new HashMap < String, String > ();
params.put("clientid", get1);
return params;
}
};
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(stringRequest);
}
Suppose date2 is eventname you want to compare.
if(date2.equals(movie.getHost())
{
// store Movie object on index 0, if it equals date2
calList.add(0, movie);
}
else
{
calList.add(movie);
}
Remove the Following Lines from caladata().
int index=calList.indexOf(date2);
calList.add(movie);
calList.remove(date2);
calList.add(0, movie);
Im using volley to get and handle the Json object into the activity
and here are the classes and the following :
The problem is when im trying to get the Address ,Phones, Emails as sorting for each line from the object it show up like this first it get the address with the first line then it jumps to line 5 to get id then line 8 to get twitterUrl.
Inside the APP Data
web Service reponse on the postman
[
{
"address": "adddress1",
"emails": "ggggdjd#ttttt.com",
"facebookUrl": "ddddd",
"googlePlus": "ddddddd",
"id": 1,
"instagramUrl": "ddddd",
"phones": "0100098763 - 82726353",
"twitterUrl": "ddddd",
"youtubeUrl": "dddd"
}
]
Content Volley.java
extends BaseVolley {
// base url for srever
String TAG = "sjnsn";
private final String url = url ;
protected enum ActionType implements BaseVolley.ActionType {
appcontactus
}
public ContentVolley(String TAG, Context context) {
super(TAG, VolleySingleton.getInstance(context));
}
// method created as an example for post request for a certain api
public void getAboutUs() {
params = new HashMap<>();
actionType = ActionType.appcontactus;
requestAction(Request.Method.GET, url + ((Enum) actionType).name(), true);
}
#Override
protected void onPreExecute(BaseVolley.ActionType actionType) {
ActionType action = (ActionType) actionType;
onPreExecute(action);
}
#Override
protected void getResponseParameters(String response) throws JSONException {
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
String message = "";
try {
jsonArray = new JSONArray(response);
Log.d(TAG, "getResponseParameters: "+response);
} catch (JSONException e) {
jsonObject = new JSONObject(response);
message = jsonObject.optString("msg");
}
ActionType action = (ActionType) actionType;
switch (action) {
case appcontactus:
ArrayList<ContactUsItem> contactUsList = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
String address = jsonObject.optString("address");
String emails = jsonObject.optString("emails");
String phones = jsonObject.optString("phones");
String facebookUrl = jsonObject.optString("facebookUrl");
String googlePlus = jsonObject.optString("googlePlus");
String instagramUrl = jsonObject.optString("instagramUrl");
String twitterUrl = jsonObject.optString("twitterUrl");
String youtubeUrl = jsonObject.optString("youtubeUrl");
String id = jsonObject.optString("id");
ContactUsItem contactUsItem = new ContactUsItem(id, address, emails, phones, facebookUrl,googlePlus,instagramUrl
,twitterUrl,youtubeUrl);
contactUsList.add(contactUsItem);
}
onPostExecuteAboutUs(true, message,contactUsList) ;
break;
}
}
#Override
protected void onPostExecuteError(boolean success, String message, BaseVolley.ActionType actionType) {
ActionType action = (ActionType) actionType;
switch (action) {
case appcontactus:
onPostExecuteAboutUs(false, message, null);
break;
}
}
protected abstract void onPreExecute(ActionType actionType);
protected void onPostExecuteAboutUs(boolean success, String message,ArrayList<ContactUsItem> contactUsList) {
}
protected void onPostExecuteappnews(boolean success, String message, Object result) {
}
}
AboutUsFragment.java
public class AboutusFragment extends Fragment {
private final String TAG = AboutusFragment.class.getSimpleName();
private RelativeLayout relativeLayoutLoading;
private TextView email;
private TextView phone;
private TextView addres;
private ImageView imageViewFacebook, imageViewInstagram, imageViewTwitter;
public AboutusFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_about_us, container, false);
relativeLayoutLoading = (RelativeLayout) rootView.findViewById(R.id.relativeLayoutLoading);
email = (TextView) rootView.findViewById(R.id.textViewEmail);
phone = (TextView) rootView.findViewById(R.id.textViewPhone);
addres = (TextView) rootView.findViewById(R.id.textViewAddress);
imageViewFacebook = (ImageView) rootView.findViewById(R.id.imageViewFacebook);
imageViewInstagram = (ImageView) rootView.findViewById(R.id.imageViewInstagram);
imageViewTwitter = (ImageView) rootView.findViewById(R.id.imageViewTwitter);
Content content = new Content();
content.getAboutUs();
return rootView;
}
private class Content extends ContentVolley {
public Content() {
super(TAG, getContext());
}
#Override
protected void onPreExecute(ActionType actionType) {
}
protected void onPostExecuteAboutUs(boolean success, String message, ArrayList<ContactUsItem> contactUsList) {
if (success) {
for (int i = 0; i < contactUsList.size(); i++) {
ContactUsItem contactUsItem = contactUsList.get(i);
email.setText(contactUsItem.getEmail());
phone.setText(contactUsItem.getPhone());
addres.setText(contactUsItem.getAddress());
}
} else {
Toast.makeText(getContext(), "Failed: " + message, Toast.LENGTH_LONG).show();
}
}
}
}
I am currently making an app where the user can access study material from a list view of different subjects.
In my database table where the subject names are fetched from also has a column which has a file path to a folder on my online server. Each subject has an individual folder on the server.
How would I go about adding to my code so that when a user clicks on a subject on the list, the content of their specific folder displays on a new activity?
here is my code at the moment of a simple list view:
public class FindMaterialActivity extends Activity {
private ListView list;
private ArrayList<String> subjects;
private JSONArray result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_material2);
list = (ListView) findViewById(R.id.list);
subjects = new ArrayList<String>();
getData();
}
private void getData() {
//Creating a string request
StringRequest stringRequest = new StringRequest(SubConfig.DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray(SubConfig.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getSubjects(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void getSubjects(JSONArray j) {
//Traversing through all the items in the json array
for (int i = 0; i < j.length(); i++) {
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
//Adding the name of the student to array list
subjects.add(json.getString(SubConfig.TAG_SUBJECTS));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
list.setAdapter(new ArrayAdapter<String>(FindMaterialActivity.this, android.R.layout.simple_list_item_1, subjects));
}
}
and subject config.java
public class SubConfig {
//JSON URL
public static final String DATA_URL = "http://opuna.co.uk/subject_api/FetchSub.php";
//Tags used in the JSON String
public static final String TAG_SUBJECTS = "Subject_Name";
public static final String TAG_SUB_ID = "Sub_id";
//JSON array name
public static final String JSON_ARRAY = "result";
}
Store the meta about the sub folders in your database as you did for subjects and get the meta using JSON in your app as you got for subjects and show them in a custom layout made of your own.
I have this code where I get the data from Facebook Graph API which seems working, my problem is when i add the hashmap to my arraylist its not working, i toasted the size of my array and I always get zero. please help. here is the code:
public class PageFeedHome extends Fragment {
ArrayList<HashMap<String, String>> feedList;
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_MESSAGE = "message";
private String feedMessage;
ListView listView;
BaseAdapter adapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.feed_home_activity,
container, false);
listView = (ListView) view.findViewById(R.id.feed_lv);
feedList = new ArrayList<HashMap<String, String>>();
new LoadPosts().execute();
return view;
}
private class LoadPosts extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
Session.openActiveSession(getActivity(), true,
new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state,
Exception exception) {
if (session.isOpened()) {
new Request(session, "/163340583656/feed",
null, HttpMethod.GET,
new Request.Callback() {
public void onCompleted(
Response response) {
/* handle the result */
Log.i("PostFeedResponse", response.toString());
try {
GraphObject graphObj = response
.getGraphObject();
JSONObject json = graphObj
.getInnerJSONObject();
JSONArray jArray = json
.getJSONArray("data");
for (int i = 0; i < jArray.length(); i++) {
JSONObject currObj = jArray.getJSONObject(i);
final String feedId = currObj.getString("id");
if (currObj.has("message")) {
feedMessage = currObj.getString("message");
} else if (currObj.has("story")) {
feedMessage = currObj.getString("story");
} else {
feedMessage = "Posted a something";
}
JSONObject fromObj = currObj.getJSONObject("from");
String from = fromObj.getString("name");
HashMap<String, String> feed = new HashMap<String, String>();
feed.put(TAG_ID, feedId);
feed.put(TAG_MESSAGE, feedMessage);
feed.put(TAG_NAME, from);
feedList.add(feed);
Log.i("added" , feedList.toString());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).executeAsync();
}
}
});
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Toast.makeText(getActivity(), ""+feedList.size(), Toast.LENGTH_LONG).show();
adapter = new SimpleAdapter(getActivity(), feedList,
R.layout.feed_item_view, new String[] { TAG_MESSAGE, TAG_NAME,
TAG_ID }, new int[] { R.id.message, R.id.author, R.id.id_tv });
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
}