I want use notifyDataSetAdpter in my list view. I read about it that i can use it when my data is updating or deleting. In my case, my whole data will show in a listView and this data i am calling from MySQL. Now, I am just displaying DB values into a list. No deletion. I want this method to show updated DB values in a list I tried using this method but it didn't work. Can you please tell me how exactly and where exactly I have to use it, in my case.
Here is my code:
See_Issue.java
package com.example.mi.mikpiadmin;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class See_Issue extends AppCompatActivity implements ListView.OnItemClickListener {
ListView listView1;
public static final String URL_GET_ISSUE = "http://10.238.4.175/new/one.php";
public static final String TAG_JSON_ARRAY="results";
public static final String TAG_ID = "id";
public static final String TAG_STORE_NAME = "store_name";
public static final String TAG_ISSUE = "issue";
public static final String TAG_DESCRIBE = "describe";
private String JSON_ISSUE_STRING;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_see__issue);
listView1=(ListView)findViewById(R.id.list_see_issue) ;
listView1.setOnItemClickListener(this);
getJSON();
}
private void showEmployee(){
JSONObject jsonObject = null;
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>();
try {
jsonObject = new JSONObject(JSON_ISSUE_STRING);
JSONArray result = jsonObject.getJSONArray(TAG_JSON_ARRAY);
for(int i = 0; i<result.length(); i++){
JSONObject jo = result.getJSONObject(i);
String id = jo.getString(TAG_STORE_NAME);
String name = jo.getString(TAG_ISSUE);
String describe = jo.getString(TAG_DESCRIBE);
HashMap<String,String> employees = new HashMap<>();
employees.put(TAG_STORE_NAME,id);
employees.put(TAG_ISSUE,name);
employees.put(TAG_DESCRIBE,describe);
list.add(employees);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(
See_Issue.this, list, R.layout.list_item,
new String[]{TAG_STORE_NAME,TAG_ISSUE,TAG_DESCRIBE},
new int[]{R.id.id, R.id.name, R.id.feedback});
listView1.setAdapter(adapter);
((ListAdapter) listView1.getAdapter()).notifyDataSetChanged();
}
private void getJSON(){
class GetJSON extends AsyncTask<Void,Void,String> {
private ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(See_Issue.this,"Fetching Data","Wait...",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
JSON_ISSUE_STRING = s;
showEmployee();
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(URL_GET_ISSUE);
return s;
}
}
GetJSON gj = new GetJSON();
gj.execute();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(this, See_Feedback.class);
HashMap<String,String> map =(HashMap)parent.getItemAtPosition(position);
String empId = map.get(Config.TAG_ID).toString();
intent.putExtra(Config.EMP_ID,empId);
startActivity(intent);
}
}
I hope you will help.
you can use adapter.notifyDataSetChanged(); :
Call notifyDataSetChanged() on your Adapter object once you've modified the data in that adapter.
It notifies the attached observers that the underlying data has been changed and any View reflecting the data set should refresh itself.
for exapmle
((BaseAdapter) yourListView.getAdapter()).notifyDataSetChanged();
or
adapter.notifyDataSetChanged();
you have to make few changes to achieve this-
1- make these global-
private ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>();
private HashMapAdapter adapter;
2- Write your own custom adapter class-
public class HashMapAdapter extends BaseAdapter {
private HashMap<String, String> mData = new HashMap<String, String>();
private String[] mKeys;
public HashMapAdapter(HashMap<String, String> data){
mData = data;
mKeys = mData.keySet().toArray(new String[data.size()]);
}
#Override
public int getCount() {
return mData.size();
}
#Override
public Object getItem(int position) {
return mData.get(mKeys[position]);
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int pos, View convertView, ViewGroup parent) {
String key = mKeys[pos];
String Value = getItem(pos).toString();
//do your view stuff here
return convertView;
}
public void updateData(HashMap<String, String> updatedData){
mData = updatedData;
mKeys = updatedData.keySet().toArray(new String[data.size()]);
//notifying dataset changed
notifyDataSetChanged();
}
}
3- change your showEmployee() method
private void showEmployee(){
JSONObject jsonObject = null;
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>();
try {
jsonObject = new JSONObject(JSON_ISSUE_STRING);
JSONArray result = jsonObject.getJSONArray(TAG_JSON_ARRAY);
for(int i = 0; i<result.length(); i++){
JSONObject jo = result.getJSONObject(i);
String id = jo.getString(TAG_STORE_NAME);
String name = jo.getString(TAG_ISSUE);
String describe = jo.getString(TAG_DESCRIBE);
HashMap<String,String> employees = new HashMap<>();
employees.put(TAG_STORE_NAME,id);
employees.put(TAG_ISSUE,name);
employees.put(TAG_DESCRIBE,describe);
list.add(employees);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter = new HashMapAdapter(list);
listView1.setAdapter(adapter);
}
4- Write an update method
private void updateAdapter((HashMap<String, String> updatedData){
//This will update the adapter data and will call the notifyDatasetChanged
apater.updatedData(updatedData);
}
Related
I tried data extraction code from many places but everywhere i get how to retrieve data in a simple list. As the structure of my JSON is complex and i can't change it now, so please help me in retrieving data from firebase database. Please help as i am not able to understand Firebase code. Following is my code and JSON database:
CategoryModel.xml
package com.example.firedb;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
/**
* Created by Android on 5/31/2017.
*/
public class CategoryModel {
private ArrayList<CategoryList> categoryList;
public CategoryModel() {
}
public CategoryModel(ArrayList<CategoryList> categoryList) {
this.categoryList = categoryList;
}
public ArrayList<CategoryList> getCategoryList() {
return categoryList;
}
public void setCategoryList(ArrayList<CategoryList> categoryList) {
this.categoryList = categoryList;
}
// CategoryList
public static class CategoryList {
public int Category_id;
public String Category_name;
public ArrayList<String>Emails;
public ArrayList<String>Epabx;
public ArrayList<String>Category_Fax;
public ArrayList<Persons> persons;
public CategoryList() {
}
//constructor of CategoryList
public CategoryList(int category_id, String category_name,
ArrayList<String> emails, ArrayList<String> epabx, ArrayList<String> category_Fax,
ArrayList<Persons> persons) {
Category_id = category_id;
Category_name = category_name;
Emails = emails;
Epabx = epabx;
Category_Fax = category_Fax;
this.persons = persons;
}
// getters and setters of CategoryList
public int getCategory_id() {
return Category_id;
}
public void setCategory_id(int category_id) {
Category_id = category_id;
}
public String getCategory_name() {
return Category_name;
}
public void setCategory_name(String category_name) {
Category_name = category_name;
}
public ArrayList<String> getEmails() {
return Emails;
}
public void setEmails(ArrayList<String> emails) {
Emails = emails;
}
public ArrayList<String> getEpabx() {
return Epabx;
}
public void setEpabx(ArrayList<String> epabx) {
Epabx = epabx;
}
public ArrayList<String> getCategory_Fax() {
return Category_Fax;
}
public void setCategory_Fax(ArrayList<String> category_Fax) {
Category_Fax = category_Fax;
}
public ArrayList<Persons> getPersons() {
return persons;
}
public void setPersons(ArrayList<Persons> persons) {
this.persons = persons;
}
}
//Persons
public static class Persons {
private int Person_ID;
private String Name;
private String Designation;
private ArrayList<String> Office_Phone;
private ArrayList<String> Residence_Phone;
private String VOIP;
private String Address;
private ArrayList<String>Fax;
private String Ext;
private ArrayList<String>Extra_info;
private String Category_name;
public Persons() {
}
// Constructor of Persons
public Persons(int person_ID, String name, String designation, ArrayList<String> office_Phone,
ArrayList<String> residence_Phone, String VOIP, String address, ArrayList<String> fax, String ext,
ArrayList<String>extra_info, String category_name) {
Person_ID = person_ID;
Name = name;
Designation = designation;
Office_Phone = office_Phone;
Residence_Phone = residence_Phone;
this.VOIP = VOIP;
Address = address;
Fax = fax;
Ext = ext;
Extra_info=extra_info;
Category_name=category_name;
}
// Getter and Setters of Persons
public int getPerson_ID() {
return Person_ID;
}
public void setPerson_ID(int person_ID) {
Person_ID = person_ID;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getDesignation() {
return Designation;
}
public void setDesignation(String designation) {
Designation = designation;
}
public ArrayList<String> getOffice_Phone() {
return Office_Phone;
}
public void setOffice_Phone(ArrayList<String> office_Phone) {
Office_Phone = office_Phone;
}
public ArrayList<String> getResidence_Phone() {
return Residence_Phone;
}
public void setResidence_Phone(ArrayList<String> residence_Phone) {
Residence_Phone = residence_Phone;
}
public String getVOIP() {
return VOIP;
}
public void setVOIP(String VOIP) {
this.VOIP = VOIP;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public ArrayList<String> getFax() {
return Fax;
}
public void setFax(ArrayList<String> fax) {
Fax = fax;
}
public String getExt() {
return Ext;
}
public void setExt(String ext) {
Ext = ext;
}
public ArrayList<String> getExtra_info() {
return Extra_info;
}
public void setExtra_info(ArrayList<String> extra_info) {
Extra_info = extra_info;
}
public String getCategory_name() {
return Category_name;
}
public void setCategory_name(String category_name) {
Category_name = category_name;
}
}
}
CardviewActivity: Earlier i used an asset file but now i want to get data from firebase whose code is ambiguous online
package com.example.firedb;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.LoginFilter;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import static android.R.attr.button;
public class CardViewActivity extends AppCompatActivity {
Toolbar mActionBarToolbar;
private RecyclerView mainRecyclerView;
private RecyclerView.Adapter mainAdapter;
private RecyclerView.LayoutManager mainLayoutManager;
private static String LOG_TAG = "CardViewActivity";
EditText inputSearchMain;
private ArrayList<CategoryModel.CategoryList> categoryLists;
TextView toolbar_title_main;
ImageView back_cardviewActivity;
// DatabaseHandler db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_card_view);
// db = new DatabaseHandler (CardViewActivity.this);
mActionBarToolbar = (Toolbar) findViewById(R.id.tool_bar);
toolbar_title_main=(TextView)findViewById(R.id.toolbar_title);
// mActionBarToolbar.setTitle("Hry. Govt. Telephone Directory");
// mActionBarToolbar.setLogo(R.drawable.logotoolbar);
// mActionBarToolbar.setTitleMargin(5,2,2,2);
setSupportActionBar(mActionBarToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar_title_main.setText("Hry. Govt. Telephone Directory");
back_cardviewActivity=(ImageView)findViewById(R.id.back);
back_cardviewActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
categoryLists=new ArrayList<CategoryModel.CategoryList>();
categoryLists.addAll(getmcategoryset());
mainRecyclerView=(RecyclerView)findViewById(R.id.recyclerView_Main);
mainRecyclerView.setHasFixedSize(true);
mainLayoutManager=new LinearLayoutManager(this);
mainRecyclerView.setLayoutManager(mainLayoutManager);
// Log.d( "onCreate: ", "List Size: "+categoryLists.size());
mainAdapter=new RecyclerViewAdapterMain(getmcategoryset());
mainRecyclerView.setAdapter(mainAdapter);
inputSearchMain = (EditText) findViewById(R.id.inputSearchMain);
addTextListener();
}
public void addTextListener(){
inputSearchMain.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence query, int start, int before, int count) {
query = query.toString().toLowerCase();
final ArrayList<CategoryModel.CategoryList> filteredList = new ArrayList<CategoryModel.CategoryList>();
for (int i = 0; i < categoryLists.size(); i++) {
final String text = categoryLists.get(i).getCategory_name().toLowerCase();
if (text.contains(query)) {
filteredList.add(categoryLists.get(i));
}
}
mainRecyclerView.setLayoutManager(new LinearLayoutManager(CardViewActivity.this));
mainAdapter = new RecyclerViewAdapterMain(filteredList);
mainRecyclerView.setAdapter(mainAdapter);
mainAdapter.notifyDataSetChanged(); // data set changed
}
});
}
private ArrayList<CategoryModel.CategoryList> getmcategoryset() {
// JSONObject obj = new JSONObject(readJSONFromAsset());
try {
ArrayList<CategoryModel.CategoryList>categoryList = new ArrayList<CategoryModel.CategoryList>();
JSONObject jsonObject = new JSONObject(readJSONFromAsset());
JSONArray categoryArray = jsonObject.getJSONArray("Category");
Log.d("getmcategoryset", "category count: "+categoryArray.length());
for (int i = 0; i < categoryArray.length(); i++)
{
JSONObject job = categoryArray.getJSONObject(i);
int categoryId = job.getInt("Category_id");
String categoryName = job.getString("Category_name");
//this is for email array
ArrayList<String> emails = new ArrayList<>();
JSONArray emailArray = job.getJSONArray("Emails");
for (int j = 0; j< emailArray.length(); j++){
// JSONObject jobE = emailArray.getString(j);
emails.add(emailArray.getString(j));
}
//This i for Epabx array
ArrayList<String> epabx = new ArrayList<>();
JSONArray epabxArray = job.getJSONArray("Epabx");
for (int j = 0; j < epabxArray.length(); j++){
// JSONObject jobE = epabxArray.getString(j);
epabx.add(epabxArray.getString(j));
}
//This i for Category_Fax array
ArrayList<String> category_Fax = new ArrayList<>();
JSONArray category_FaxJson = job.getJSONArray("Category_Fax");
for (int j = 0; j < category_FaxJson.length(); j++){
// JSONObject jobE = category_FaxJson.getString(j);
category_Fax.add(category_FaxJson.getString(j));
}
//This i for Persons array
ArrayList<CategoryModel.Persons> personsList = new ArrayList<>();
JSONArray personsArray = job.getJSONArray("Persons");
for (int j = 0; j < personsArray.length(); j++){
JSONObject jobIn = personsArray.getJSONObject(j);
int Person_ID = jobIn.getInt("Person_ID");
String Name = jobIn.getString("Name");
String Designation = jobIn.getString("Designation");
//this is for Office_Phone array
ArrayList<String>Office_Phone = new ArrayList<>();
JSONArray office_Phone = jobIn.getJSONArray("Office_Phone");
for (int k=0; k < office_Phone.length(); k++)
{
Office_Phone.add(office_Phone.getString(k));
}
//this is for Residence_Phone array
ArrayList<String>Residence_Phone = new ArrayList<>();
JSONArray residence_Phone = jobIn.getJSONArray("Residence_Phone");
for (int k=0; k < residence_Phone.length(); k++)
{
Residence_Phone.add(residence_Phone.getString(k));
}
String VOIP = jobIn.getString("VOIP");
String Address = jobIn.getString("Address");
//this is for Fax array
ArrayList<String>Fax = new ArrayList<>();
JSONArray fax = jobIn.getJSONArray("Fax");
for (int k=0; k < fax.length(); k++)
{
Fax.add(fax.getString(k));
}
String Ext = jobIn.getString("Ext");
//this is for Extra_info array
ArrayList<String>Extra_info = new ArrayList<>();
JSONArray extra_info = jobIn.getJSONArray("Extra_info");
for (int k=0; k < extra_info.length(); k++)
{
Extra_info.add(extra_info.getString(k));
}
personsList.add(new CategoryModel.Persons(Person_ID, Name, Designation, Office_Phone, Residence_Phone,
VOIP, Address, Fax, Ext,Extra_info,categoryName));
// db.addPerson(new CategoryModel.Persons(Person_ID, Name, Designation, Office_Phone, Residence_Phone,
// VOIP, Address, Fax, Ext,Extra_info));
}
//here your Category[] value store in categoryArrayList
categoryList.add(new CategoryModel.CategoryList(categoryId, categoryName, emails, epabx, category_Fax, personsList));
// db.addCategory(new CategoryModel.CategoryList(categoryId, categoryName, emails, epabx, category_Fax, personsList));
Log.i("categoryList size = ", ""+categoryArray.length());
Log.i("cat_name=",""+categoryName);
}
if (categoryList != null)
{
Log.i("categoryList size = ", ""+categoryArray.length());
}
return categoryList;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onResume() {
super.onResume();
// ((RecyclerViewAdapterMain) mainAdapter).setOnItemClickListener(new RecyclerViewAdapterMain()
// .CategoryClickListener() {
// public void onItemClick(int position, View v) {
// Log.i(LOG_TAG, " Clicked on Item " + position);
// }
// });
}
}
RecyclerViewAdapter:
package com.example.firedb;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
public class RecyclerViewAdapterMain extends RecyclerView.Adapter<RecyclerViewAdapterMain.CategoryObjectHolder> {
private static String LOG_TAG = "categoryRecyclrVwAdptr";
private ArrayList<CategoryModel.CategoryList> mcategoryset;
private static CategoryClickListener categoryClickListener;
public static class CategoryObjectHolder extends RecyclerView.ViewHolder {
TextView category_name;
/*TextView category_emails;
TextView category_epabx;
TextView category_fax;*/
public CategoryObjectHolder(View itemView){
super(itemView);
category_name=(TextView)itemView.findViewById(R.id.category_name);
/*category_emails=(TextView)itemView.findViewById(R.id.category_emails);
category_epabx=(TextView)itemView.findViewById(R.id.category_epabx);
category_fax=(TextView)itemView.findViewById(R.id.category_fax);*/
Log.i(LOG_TAG, "Adding Listener");
}
// #Override
// public void onClick(View v) {
// categoryClickListener.onItemClick(getAdapterPosition(), v);
// }
}
// public void setOnItemClickListener(CategoryClickListener categoryClickListener) {
// this.categoryClickListener = categoryClickListener;
// }
public RecyclerViewAdapterMain(ArrayList<CategoryModel.CategoryList> myDataset) {
mcategoryset = myDataset;
}
public CategoryObjectHolder onCreateViewHolder(ViewGroup parent,int viewType){
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view_row_main_activity,parent,false);
CategoryObjectHolder categoryObjectHolder=new CategoryObjectHolder(view);
return categoryObjectHolder;
}
#Override
public void onBindViewHolder(CategoryObjectHolder holder, final int position) {
/*final StringBuilder stringBuilder_emails = new StringBuilder();
for (String email : mcategoryset.get(position).getEmails()) {
if (!stringBuilder_emails.toString().isEmpty()) {
stringBuilder_emails.append(", ");
}
stringBuilder_emails.append(email);
}
final StringBuilder stringBuilder_Epabx = new StringBuilder();
for (String epabx : mcategoryset.get(position).getEpabx()) {
if (!stringBuilder_Epabx.toString().isEmpty()) {
stringBuilder_Epabx.append(", ");
}
stringBuilder_Epabx.append(epabx);
}
final StringBuilder stringBuilder_Category_Fax = new StringBuilder();
for (String category_Fax : mcategoryset.get(position).getCategory_Fax()) {
if (!stringBuilder_Category_Fax.toString().isEmpty()) {
stringBuilder_Category_Fax.append(", ");
}
stringBuilder_Category_Fax.append(category_Fax);
}*/
holder.category_name.setText(mcategoryset.get(position).getCategory_name());
/*holder.category_emails.setText(stringBuilder_emails.toString());
holder.category_epabx.setText(stringBuilder_Epabx.toString());
holder.category_fax.setText(stringBuilder_Category_Fax.toString());*/
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent (v.getContext(), PeopleListActivity.class);
i.putParcelableArrayListExtra("Persons",mcategoryset.get(position).getPersons());
i.putStringArrayListExtra("emails",mcategoryset.get(position).getEmails());
//i.putExtras(b);
v.getContext().startActivity(i);
}
});
}
public void addItem(CategoryModel.CategoryList dataObj, int index) {
mcategoryset.add(index, dataObj);
notifyItemInserted(index);
}
public void deleteItem(int index) {
mcategoryset.remove(index);
notifyItemRemoved(index);
}
#Override
public int getItemCount() {
return mcategoryset.size();
}
public interface CategoryClickListener {
public void onItemClick(int position, View v);
}
}
The only way to get data from Firebase Database it's using a ValueEventListener.
Firebase work with asynchronous calls, so you can't call the function, get the data and use it. You have to set a ValueEventListener in a specific database reference.
For your actual problem, you have to create an array, set the Firebase Reference, add the ValueEventListener and inside add each occurrence of CategoryList in the array. Finally , still inside of the ValueEventListener, you can create your CategoryModel, with the CategoryList's array as parameter, and update your UI, to see the data in CategoryModel:
CategoryModel categoryModel;
ArrayList<CategoryList> array = new ArrayList<>();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference categoryRef = database.getReference("Category");
categoryRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
CategoryList categoryList = childSnapshot.getValue(CategoryList.class);
array.add(categoryList);
}
categoryModel = new CategoryModel(array);
// Method to show the data in category model,
// usually populating an ListView or something
updateUI()
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
For have this working, your CategoryList class has to implement all the setters of his members so "datasnapshot.getValue()" works.
Another approach can be, create a Constructor in CategoryList that recibe a DataSnapshot in this way:
public CategoryList(DataSnapshot snapshot){
Category_id = snapshot.child("Category_id").getValue(int.class);
Category_name = snapshot.child("Category_name").getValue(String.class);
GenericTypeIndicator<List<String>> stringList = new GenericTypeIndicator<List<String>>() {};
Emails = snapshot.child("Emails").getValue(stringList);
Epabx= snapshot.child("Epabx").getValue(stringList);
Category_Fax= snapshot.child("Category_Fax").getValue(stringList);
GenericTypeIndicator<List<Persons>> personsList = new GenericTypeIndicator<List<Persons>>() {};
persons = snapshot.child("Persons").getValue(personsList);
}
If you create the constructor, you have to replace this line:
CategoryList categoryList = childSnapshot.getValue(CategoryList.class);
with this:
CategoryList categoryList = new CategoryList(childSnapshot);
You can see that I use GenericTypeIndicator to work with collections of data, this is a helper class provide for Firebase to work with Lists, Maps, Sets or another Collection.
Just a recommendation! This is not a good data structure, you should denormalize your data.Then you can observe your data by ChildEventListener or ValueEventListener.
For example:
-Category
--CategoryId
---CategoryList
---Persons
----user1: true
----user2: true, etc.
-Users
--user1Id
---user1details
--user2Id
---user2details, etc.
Here is some useful links about denormalizing your data
Link1,
Link2
I am using the library asymmetricGridView,
The code given:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (AsymmetricGridView) findViewById(R.id.listView);
// Choose your own preferred column width
listView.setRequestedColumnWidth(Utils.dpToPx(this, 120));
final List<AsymmetricItem> items = new ArrayList<>();
// initialize your items array
adapter = new ListAdapter(this, listView, items);
AsymmetricGridViewAdapter asymmetricAdapter =
new AsymmetricGridViewAdapter<>(this, listView, adapter);
listView.setAdapter(asymmetricAdapter);
}
I am getiing an error in adapter = new ListAdapter(this, listView, items);
I don't know how to use ListAdapter, I am new to android, can anyone help me go about it?
ListAdapter is an interface, not a class. You cannot instantiate it with new, unless you are defining an anonymous inner class at the point of instantiation.
I suggest you do some searching for tutorials about using ListAdapter (and adapters on Android in general). I also recommend you use the AsymmetricRecyclerView instead from that same library (and therefore also the AsymmetricRecyclerViewAdapter) because ListView is rather old and clunky and it's functionality has been more or less superseded by RecyclerView.
This is result
Step 1: Create class Events.
import java.io.Serializable;
public class Events implements Serializable {
private String id;
private String titleEvent;
private String dateEvent;
public Events() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitleEvent() {
return titleEvent;
}
public void setTitleEvent(String titleEvent) {
this.titleEvent = titleEvent;
}
public String getDateEvent() {
return dateEvent;
}
public void setDateEvent(String dateEvent) {
this.dateEvent = dateEvent;
}
}
Step2: Create class ListAdapter extends ArrayAdapter<Events>
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.info.quanglv.eventlucky.R;
import com.info.quanglv.eventlucky.common.Events;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class ListAdapter extends ArrayAdapter<Events> {
List<Events> listProduct = new ArrayList<>();
public ListAdapter(Context context, int resource, List<Events> objects) {
super(context, resource, objects);
listProduct = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
view = inflater.inflate(R.layout.item_events, null);
}
Events events = getItem(position);
if (events != null) {
TextView txt_Title = (TextView) view.findViewById(R.id.txtTitleEvent);
txt_Title.setText(events.getTitleEvent());
TextView txt_dateEvent = (TextView) view.findViewById(R.id.txtDateEvent);
txt_dateEvent.setText(events.getDateEvent());
//ImageView img_Product = (ImageView) view.findViewById(R.id.imgProduct);
// img_Product.setImageResource(position);
// img_Product.setImageURI(product.getImg());
// new DownloadImageTask(img_Product).execute(listProduct.get(position).getImageProduct());
}
return view;
}
public static class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
Step 3: in onCreate() you can code:
new GetListProduct().execute();
private class GetListProduct extends AsyncTask<Void, Void, ArrayList<Events>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected ArrayList<Events> doInBackground(Void... params) {
ArrayList<Events> events = new ArrayList<>();
Events eventsLucky = new Events();
eventsLucky.setId("1");
eventsLucky.setTitleEvent("New Year CountDown Party");
eventsLucky.setDateEvent("10/10/12");
events.add(eventsLucky);
Events eventsLucky1 = new Events();
eventsLucky1.setId("2");
eventsLucky1.setTitleEvent("Tiger Remix Concert 2016 ");
eventsLucky1.setDateEvent("10/10/12");
events.add(eventsLucky1);
Events eventsLucky2 = new Events();
eventsLucky2.setId("3");
eventsLucky2.setTitleEvent("Tiger Remix Concert 2016 ");
eventsLucky2.setDateEvent("10/10/1212");
events.add(eventsLucky2);
Events eventsLucky3 = new Events();
eventsLucky3.setId("4");
eventsLucky3.setTitleEvent("Tiger Remix Concert 2016 ");
eventsLucky3.setDateEvent("10/10/1212");
events.add(eventsLucky3);
return events;
}
#Override
protected void onPostExecute(ArrayList<Events> events) {
super.onPostExecute(events);
listView = (ListView) findViewById(R.id.listView);
ListAdapter listAdapter = new ListAdapter(HomeActivity.this, R.layout.activity_home_activiy, events);
listView.setAdapter(listAdapter);
}
}
Step 4: Insert code under onCreate()
private class GetListProduct extends AsyncTask<Void, Void, ArrayList<Events>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected ArrayList<Events> doInBackground(Void... params) {
ArrayList<Events> events = new ArrayList<>();
Events eventsLucky = new Events();
eventsLucky.setId("1");
eventsLucky.setTitleEvent("New Year CountDown Party");
eventsLucky.setDateEvent("10/10/12");
events.add(eventsLucky);
Events eventsLucky1 = new Events();
eventsLucky1.setId("2");
eventsLucky1.setTitleEvent("Tiger Remix Concert 2016 ");
eventsLucky1.setDateEvent("10/10/12");
events.add(eventsLucky1);
Events eventsLucky2 = new Events();
eventsLucky2.setId("3");
eventsLucky2.setTitleEvent("Tiger Remix Concert 2016 ");
eventsLucky2.setDateEvent("10/10/1212");
events.add(eventsLucky2);
Events eventsLucky3 = new Events();
eventsLucky3.setId("4");
eventsLucky3.setTitleEvent("Tiger Remix Concert 2016 ");
eventsLucky3.setDateEvent("10/10/1212");
events.add(eventsLucky3);
return events;
}
#Override
protected void onPostExecute(ArrayList<Events> events) {
super.onPostExecute(events);
listView = (ListView) findViewById(R.id.listView);
ListAdapter listAdapter = new ListAdapter(HomeActivity.this, R.layout.activity_home_activiy, events);
listView.setAdapter(listAdapter);
}
}
I'm using web domain to parsed data and passed it to my android listview. How can i load data only on first run so when i clicked again the tab it will not load again the data from the web and the listview will be populated already? Is it possible?
package com.example.work.mcoatorderingapplication;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends ActionBarActivity {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
public static final JSONParser jParser = new JSONParser();
private static final String GET_SUCCESS = "success";
private static final String GET_MESSAGE = "message";
//FOR ALL PRODUCTS
private ArrayList<HashMap<String, String>> orderlist;
private static final String PRODUCTLIST_URL = "http://alliedpaint-001-site1.smarterasp.net/productlist.php";
private static final String ORDER_URL = "http://alliedpaint-001-site1.smarterasp.net/insertorder.php";
static final String GET_PRODUCT = "message";
static final String GET_ID = "ID";
static final String GET_BRAND = "Brand";
static final String GET_CATEGORY = "Category";
static final String GET_DESCRIPTION = "Description";
static final String GET_CODE = "Code";
static final String GET_QUANTITY = "Quantity";
static final String GET_UNIT = "Unit";
static final String GET_UNITPRICE = "Unitprice";
static final String GET_IMAGE = "Image";
static final String GET_TOTAL = "Total";
ProgressDialog pDialog;
Toolbar toolbar;
ViewPager pager;
ViewPagerAdapter adapter;
ListViewAdapter ladapter;
SlidingTabLayout tabs;
CharSequence Titles[];
int Numboftabs = 4;
ListView lv,lv1;
ImageLoader imageloader;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.activity_main);
username =getIntent().getStringExtra("Username");
password =getIntent().getStringExtra("Password");
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
adapter = new ViewPagerAdapter(MainActivity.this, getSupportFragmentManager(), Titles, Numboftabs);
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
// Assiging the Sliding Tab Layout View
tabs=(SlidingTabLayout)
findViewById(R.id.tabs);
tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
// Setting Custom Color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer()
{
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
}
);
// Setting the ViewPager For the SlidingTabsLayout
tabs=(SlidingTabLayout)findViewById(R.id.tabs);
tabs.setCustomTabView(R.layout.custom_tab, 0);
tabs.setViewPager(pager);
pagelistener.onPageSelected(0);
pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (position == 0) {
new LoadProducts().execute();
} else if (position == 1) {
new LoadCart().execute();
} else if (position == 2) {
new LoadOrderStatus().execute();
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
checkconnection= new CheckInternet(getApplicationContext());
}
//LOAD ALL PRODUCTS ON THE FIRST LOAD
final ViewPager.OnPageChangeListener pagelistener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if(position==0){
new LoadProducts().execute();
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
private void updateproductlist() {
listview = (ListView) findViewById(R.id.listviewproduct);
ladapter = new ListViewAdapter(MainActivity.this, orderlist);
listview.setAdapter(ladapter);
listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, final View view,
int posistion, long id) {
final EditText input = new EditText(MainActivity.this);
final String Quantity = ((TextView) view.findViewById(R.id.Quantity)).getText().toString();
final String Brand = ((TextView) view.findViewById(R.id.Brand)).getText().toString();
final String Category = ((TextView) view.findViewById(R.id.Category)).getText().toString();
final String Code = ((TextView) view.findViewById(R.id.Code)).getText().toString();
final String Description = ((TextView) view.findViewById(R.id.Description)).getText().toString();
final String Unit = ((TextView) view.findViewById(R.id.Unit)).getText().toString();
final String Price = ((TextView) view.findViewById(R.id.Price)).getText().toString();
class InsertOrder extends AsyncTask<String, String, String> {
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Moving to Cart...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
int success;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Quantity", input.getText().toString()));
params.add(new BasicNameValuePair("Brand", Brand));
params.add(new BasicNameValuePair("Category", Category));
params.add(new BasicNameValuePair("Code", Code));
params.add(new BasicNameValuePair("Description", Description));
params.add(new BasicNameValuePair("Unit", Unit));
params.add(new BasicNameValuePair("Unitprice", Price));
JSONObject json = jParser.makeHttpRequest(
ORDER_URL, "POST", params);
success = json.getInt(GET_SUCCESS);
if (success == 0) {
return json.getString(GET_MESSAGE);
} else {
return json.getString(GET_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog1
* **/
protected void onPostExecute(String file_url) {
// dismiss the dia1log once product deleted
pDialog.dismiss();
if (file_url != null) {
Toast.makeText(MainActivity.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setTitle("Enter Quantity");
alert.setView(input);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
input.setText(Quantity);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
if (input.getText().toString().equals("")) {
Toast.makeText(MainActivity.this, "Enter Quantity first", Toast.LENGTH_LONG).show();
} else {
if (Integer.parseInt(input.getText().toString()) <= 0) {
Toast.makeText(MainActivity.this, "Invalid Quantity", Toast.LENGTH_LONG).show();
} else {
new InsertOrder().execute();
}
}
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alert.show();
return true;
}
});
}
public void UpdateJsonProduct(){
orderlist = new ArrayList<HashMap<String, String>>();
JSONObject json = jParser.getJSONFromUrl(PRODUCTLIST_URL);
try {
order = json.getJSONArray(GET_PRODUCT);
for (int i = 0; i < order.length(); i++) {
JSONObject c = order.getJSONObject(i);
String id = c.getString(GET_ID);
String brand = c.getString(GET_BRAND);
String category = c.getString(GET_CATEGORY);
String code = c.getString(GET_CODE);
String description = c.getString(GET_DESCRIPTION);
String quantity = c.getString(GET_QUANTITY);
String unit = c.getString(GET_UNIT);
String unitprice = c.getString(GET_UNITPRICE);
String image = c.getString(GET_IMAGE);
HashMap<String, String> map = new HashMap<String, String>();
map.put(GET_ID,id);
map.put(GET_BRAND, brand);
map.put(GET_CATEGORY, category);
map.put(GET_CODE, code);
map.put(GET_DESCRIPTION, description);
map.put(GET_QUANTITY, quantity);
map.put(GET_UNIT, unit);
map.put(GET_UNITPRICE, unitprice);
map.put(GET_IMAGE,image);
orderlist.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
final public class LoadProducts extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Boolean doInBackground(Void... arg0) {
UpdateJsonProduct();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
pDialog.dismiss();
updateproductlist();
}
}
}
Create this variable
boolean isDataLoaded = false;
Your onPageSelected method would be:
#Override
public void onPageSelected(int position) {
if(position==0){
if(!isDataLoaded)
new LoadProducts().execute();
}
}
And update variable isDataLoaded to true when you populate listview correctly in your PostExecute of LoadProducts Asynctask:
updateproductlist();
isDataLoaded = true;
Or in your method updateproductlist, you can decide
I am new android now I want to display image from an url. I am using imageview in listview. I want to add the list of images into the each row of the list item. I used SimpleAdapter but the imageview shows blank.
Here's the main activity:
package com.example.mysqltest;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class ReadComments extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// testing on Emulator:
private static final String READ_COMMENTS_URL = "http://192.168.30.198/test/webservice/comments.php";
// JSON IDS:
private static final String TAG_SUCCESS = "success";
private static final String TAG_TITLE = "title";
private static final String TAG_POSTS = "posts";
private static final String TAG_POST_ID = "post_id";
private static final String TAG_USERNAME = "username";
private static final String TAG_MESSAGE = "message";
private static final String TAG_IMAGE = "image";
// An array of all of our comments
private JSONArray mComments = null;
// manages all of our comments in a list.
private ArrayList<HashMap<String, String>> mCommentList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// note that use read_comments.xml instead of our single_post.xml
setContentView(R.layout.read_comments);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
// loading the comments via AsyncTask
new LoadComments().execute();
}
public void addComment(View v) {
Intent i = new Intent(ReadComments.this, AddComment.class);
startActivity(i);
}
/**
* Retrieves recent post data from the server.
*/
public void updateJSONdata() {
mCommentList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);
try {
mComments = json.getJSONArray(TAG_POSTS);
for (int i = 0; i < mComments.length(); i++) {
JSONObject c = mComments.getJSONObject(i);
// gets the content of each tag
String title = c.getString(TAG_TITLE);
String content = c.getString(TAG_MESSAGE);
String username = c.getString(TAG_USERNAME);
String image = c.getString(TAG_IMAGE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
map.put(TAG_MESSAGE, content);
map.put(TAG_USERNAME, username);
map.put(TAG_IMAGE, image);
// adding HashList to ArrayList
mCommentList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Inserts the parsed data into the listview.
*/
private void updateList() {
ListAdapter adapter = new SimpleAdapter(this, mCommentList,
R.layout.single_post, new String[] { TAG_TITLE, TAG_MESSAGE,
TAG_USERNAME,TAG_IMAGE }, new int[] { R.id.title, R.id.message,
R.id.username, R.id.imageView1 });
// I shouldn't have to comment on this one:
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {}
});
}
public class LoadComments extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ReadComments.this);
pDialog.setMessage("Loading Comments...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Boolean doInBackground(Void... arg0) {
updateJSONdata();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
pDialog.dismiss();
updateList();
}
}
}
add this code just after the setContentView(R.layout.read_comments); on your MainActivity
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
and the IDE will automatically ask you to import android.os.StrictMode library.
and think about using a base adapter
I have an app with three fragments which I need to Asynctask every swipe. But it seems that the Asynctask runs only on the opening of the app. But when it's already created, only the first and third fragment functions well when it comes to AsyncTask the second doesn't change when I update the database.
This is my MainActivity.java
package com.example.RadarOperationMonitoringSystem;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
/**
* Created by Lemueloodle on 2/12/14.
*/
public class MainActivity extends FragmentActivity{
ViewPager Tab;
TabPagerAdapter TabAdapter;
ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TabAdapter = new TabPagerAdapter(getSupportFragmentManager());
Tab = (ViewPager)findViewById(R.id.viewPager);
Tab.setOnPageChangeListener(
new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar = getActionBar();
actionBar.setSelectedNavigationItem(position); }
});
Tab.setAdapter(TabAdapter);
actionBar = getActionBar();
//Enable Tabs on Action Bar
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.TabListener tabListener = new ActionBar.TabListener(){
#Override
public void onTabReselected(android.app.ActionBar.Tab tab,
FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
Tab.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(android.app.ActionBar.Tab tab,
FragmentTransaction ft) {
// TODO Auto-generated method stub
}};
//Add New Tab
actionBar.addTab(actionBar.newTab().setText("FirstFragment").setTabListener(tabListener));
actionBar.addTab(actionBar.newTab().setText("SecondFragment").setTabListener(tabListener));
actionBar.addTab(actionBar.newTab().setText("ThirdFragment").setTabListener(tabListener));
}
}
This is my TabPagerAdapter
package com.example.RadarOperationMonitoringSystem;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
/**
* Created by Lemueloodle on 2/12/14.
*/
public class TabPagerAdapter extends FragmentStatePagerAdapter {
public TabPagerAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
#Override
public Fragment getItem(int i) {
switch(i) {
case 0:
return new FirstFragment();
case 1:
return new SecondFragment();
case 2:
return new ThirdFragment();
}
return null;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 3; //No of Tabs
}
}
This is my FirstFragment.java
package com.example.RadarOperationMonitoringSystem;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class FirstFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View first = inflater.inflate(R.layout.first_frag, container, false);
// get the listview
((TextView)first.findViewById(R.id.textView)).setText("SecondFragment");
return first;
}
}
SecondFragment.java
package com.example.RadarOperationMonitoringSystem;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class SecondFragment extends ListFragment {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static final String url = "http://10.0.2.2/radaroperations/networkstatus.php";
private static final String TAG_SITENAME1 = "siteName1";
private static final String TAG_NETSTAT1 = "netlink_stats1";
private static final String TAG_FORECAST1 = "forcasting_stats1";
private static final String TAG_MDSI1 = "pagasa_mdsi_stats1";
private static final String TAG_PNOAH1 = "projectnoah_stats1";
....so on
String site1 = "";
String netstat1 = "";
String forecast1 = "";
String mdsi1 = "";
String pnoah1 = "";
.....so on
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View second = inflater.inflate(R.layout.second_frag, container, false);
((TextView)second.findViewById(R.id.textView)).setText("SecondFragment");
return second;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// We set clear listener
new GetContactsb().execute();
}
public class GetContactsb extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(true);
pDialog.show();
}
#Override
public Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler2 sh = new ServiceHandler2();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler2.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject c = new JSONObject(jsonStr);
// Getting JSON Array node
site1 = c.getString(TAG_SITENAME1);
netstat1 = c.getString(TAG_NETSTAT1);
forecast1 = c.getString(TAG_FORECAST1);
mdsi1 = c.getString(TAG_MDSI1);
pnoah1 = c.getString(TAG_PNOAH1);
..so on
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_SITENAME1, site1);
contact.put(TAG_NETSTAT1, netstat1);
contact.put(TAG_FORECAST1, forecast1);
contact.put(TAG_MDSI1, mdsi1);
contact.put(TAG_PNOAH1, pnoah1);
...so on
// adding contact to contact list
contactList.clear();
contactList.add(contact);
} catch (JSONException e) {
e.printStackTrace();
}
}else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
public void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
*
*/
ListAdapter adapter = new SimpleAdapter(
getActivity(), contactList,
R.layout.list_item2, new String[] { TAG_SITENAME1,TAG_SITENAME2,TAG_SITENAME3,TAG_SITENAME4,
TAG_SITENAME5,TAG_SITENAME6,TAG_SITENAME7},
new int[] { R.id.sitename1, R.id.sitename2, R.id.sitename3, R.id.sitename4,R.id.sitename5,
R.id.sitename6, R.id.sitename7}){
//This will change the color of the value depending on the limit given
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView netstata = (TextView) view.findViewById(R.id.netstat1);
TextView forecasta = (TextView) view.findViewById(R.id.forecast1);
TextView mdsia = (TextView) view.findViewById(R.id.pmdsi1);
TextView pnoaha = (TextView) view.findViewById(R.id.pnoah1);
....so on
//1 - Red = No link
//2 - Yellow = Delay
//3 - Green = Good
//Radar 1
//Network Link Status
if (netstat1.equals("1")){
netstata.setText("No-Link");
netstata.setTextColor(getResources().getColor(R.color.red));
}
else if(netstat1.equals("2")){
netstata.setText("Delay");
netstata.setTextColor(getResources().getColor(R.color.yellow));
}
else if(netstat1.equals("3")){
netstata.setText("Good");
netstata.setTextColor(getResources().getColor(R.color.green));
}
...so on to Radar 7
return view;
};
};
// updating listviews
setListAdapter(adapter);
}
}
}
ThirdFragment.java
package com.example.RadarOperationMonitoringSystem;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class ThirdFragment extends ListFragment {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static final String url = "http://10.0.2.2/radaroperations/energyreadings.php";
private static final String TAG_SITENAME1 = "siteName1";
private static final String TAG_FREQUENCY1 = "Frequency1";
private static final String TAG_ACCURRENT1 = "AC_Voltage1";
private static final String TAG_ACVOLTAGE1 = "AC_Current1";
private static final String TAG_FSTAT1 = "Flimitstat1";
private static final String TAG_VSTAT1 = "Vlimitstat1";
private static final String TAG_CSTAT1 = "Climitstat1";
...so on
// contacts JSONArray
JSONObject c = null;
String site1 = "";
String freq1 = "";
String curr1 = "";
String volts1 = "";
String fstat1 = "";
String vstat1 = "";
String cstat1 = "";
.. so on
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View third = inflater.inflate(R.layout.third_frag, container, false);
((TextView)third.findViewById(R.id.textView)).setText("ThirdFragment");
return third;
}
public void StartProgress() {
new GetContactsc().execute();
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// We set clear listener
new GetContactsc().execute();
}
public class GetContactsc extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(true);
pDialog.show();
}
#Override
public Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler3 sh = new ServiceHandler3();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler3.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject c = new JSONObject(jsonStr);
// Getting JSON Array node
site1 = c.getString(TAG_SITENAME1);
freq1 = c.getString(TAG_FREQUENCY1);
curr1 = c.getString(TAG_ACCURRENT1);
volts1 = c.getString(TAG_ACVOLTAGE1);
fstat1 = c.getString(TAG_FSTAT1);
vstat1 = c.getString(TAG_VSTAT1);
cstat1 = c.getString(TAG_CSTAT1);
...so on
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_SITENAME1, site1);
contact.put(TAG_FREQUENCY1, freq1);
contact.put(TAG_ACCURRENT1, curr1);
contact.put(TAG_ACVOLTAGE1, volts1);
contact.put(TAG_FSTAT1, fstat1);
contact.put(TAG_VSTAT1, vstat1);
contact.put(TAG_CSTAT1, cstat1);
...so on
// adding contact to contact list
contactList.clear();
contactList.add(contact);
} catch (JSONException e) {
e.printStackTrace();
}
}else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
public void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
*
*/
ListAdapter adapter = new SimpleAdapter(
getActivity(), contactList,
R.layout.list_item, new String[] { TAG_SITENAME1, TAG_FREQUENCY1, TAG_ACCURRENT1,
TAG_ACVOLTAGE1,TAG_SITENAME2, TAG_FREQUENCY2, TAG_ACCURRENT2,
TAG_ACVOLTAGE2,TAG_SITENAME3, TAG_FREQUENCY3, TAG_ACCURRENT3,
TAG_ACVOLTAGE3, TAG_SITENAME4, TAG_FREQUENCY4, TAG_ACCURRENT4,
TAG_ACVOLTAGE4, TAG_SITENAME5, TAG_FREQUENCY5, TAG_ACCURRENT5,
TAG_ACVOLTAGE5, TAG_SITENAME6, TAG_FREQUENCY6, TAG_ACCURRENT6,
TAG_ACVOLTAGE6, TAG_SITENAME7, TAG_FREQUENCY7, TAG_ACCURRENT7,
TAG_ACVOLTAGE7},
new int[] { R.id.sitename1, R.id.frequency1,
R.id.accurrent1, R.id.acvoltage1, R.id.sitename2, R.id.frequency2,
R.id.accurrent2, R.id.acvoltage2, R.id.sitename3, R.id.frequency3,
R.id.accurrent3, R.id.acvoltage3, R.id.sitename4, R.id.frequency4,
R.id.accurrent4, R.id.acvoltage4, R.id.sitename5, R.id.frequency5,
R.id.accurrent5, R.id.acvoltage5, R.id.sitename6, R.id.frequency6,
R.id.accurrent6, R.id.acvoltage6, R.id.sitename7, R.id.frequency7,
R.id.accurrent7, R.id.acvoltage7}){
//This will change the color of the value depending on the limit given
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView freqa = (TextView) view.findViewById(R.id.frequency1);
TextView voltsa = (TextView) view.findViewById(R.id.acvoltage1);
TextView curra = (TextView) view.findViewById(R.id.accurrent1);
... so on
//Radar 1
if (fstat1.equals("1")){
freqa.setTextColor(getResources().getColor(R.color.green));
}
else if(fstat1.equals("2")){
freqa.setTextColor(getResources().getColor(R.color.red));
}
if(vstat1.equals("1")){
voltsa.setTextColor(getResources().getColor(R.color.green));
}
else if(vstat1.equals("2")){
voltsa.setTextColor(getResources().getColor(R.color.red));
}
if(cstat1.equals("1")){
curra.setTextColor(getResources().getColor(R.color.green));
}
else if(cstat1.equals("2")){
curra.setTextColor(getResources().getColor(R.color.red));
}
... so on to Radar 7
return view;
};
};
// updating listviews
setListAdapter(adapter);
}
}
}
I had the same problem like u. I think that problem is because ViewPager saves states of last and next pager, and building them before they come. Try setting tab.setOffscreenPageLimit(0). By doing that u may encounter problem that when ever u swipe pages, pages will be rebuild.