As I can change the setContentView if I 'm in a Fragment
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.j_01_list);
new ProgressTask(jornada.this).execute();
}
If you are a Fragment you can set your view calling onCreateView() like
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.j_01_list, container, false);
}
but this only will happens if you extends from FRAGMENT
Example of a Fragment
public class TestFragment extends Fragment {
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.j_01_list, container, false);
return rootView;
}
}
For more information check this Fragment Documentation and onCreateView() Documentation
package com.aab;
import android.app.ListActivity;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
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 jornada extends ListFragment {
private Context context;
private static String url = "http://cadetes.esy.es/conexion/jornadas/j01.php";
private static final String FECHA = "fecha";
private static final String HORA = "hora";
private static final String LOCAL = "nomLocal";
private static final String RLOCAL = "resulLocal";
private static final String RVISI = "resulVisitante";
private static final String VISI = "nomVisitante";
private static final String ESTADO = "estadoPartido";
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
ListView lv ;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.j_01_list, container, false);
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
public ProgressTask(ListActivity activity) {
Log.i("1", "Called");
context = activity;
dialog = new ProgressDialog(context);
}
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Iniciando....");
this.dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
ListAdapter adapter = new SimpleAdapter(context, jsonlist, R.layout.jornadas_row,
new String[]{FECHA, HORA, LOCAL, RLOCAL, VISI, ESTADO}, new int[]
{R.id.tv_fecha, R.id.tv_hora, R.id.tv_local, R.id.tv_result, R.id.tv_visitante, R.id.tv_espacio});
setListAdapter(adapter);
lv = getListView();
}
protected Boolean doInBackground(final String... args) {
JSONParser jParser = new JSONParser();
JSONArray json = jParser.getJSONFromUrl(url);
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
String vfecha = ("Fecha: " + c.getString(FECHA));
String vhora = ("Hora: " + c.getString(HORA));
String vlocal = c.getString(LOCAL);
String vrlocal = (c.getString(RLOCAL) + (" - " + c.getString(RVISI)));
String vrvisi = c.getString(RVISI);
String vvisi = c.getString(VISI);
String vestado = c.getString(ESTADO);
HashMap<String, String> map = new HashMap<String, String>();
map.put(FECHA, vfecha);
map.put(HORA, vhora);
map.put(LOCAL, vlocal);
map.put(RLOCAL, vrlocal);
map.put(RVISI, vrvisi);
map.put(VISI, vvisi);
map.put(ESTADO, vestado);
jsonlist.add(map);
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
}
}
Related
I checked all the previous questions regarding this issue, but none of them are helpful to me.
I am trying to open new activity in my listview onItemClickListener but it is not opening the new activity. In the android monitor, it shows
"D/ViewRootImpl: ViewPostImeInputStage ACTION_DOWN".
The onItemClickListener is not responding when I click that item of my listview... Is it possible to open?
The activity is successfully running, but I am unable to listen for list click events.
How to correct this?
Here is my class :
import android.app.ProgressDialog;
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.preference.PreferenceManager;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.banyan.simtaa_erp.R;
import com.example.banyan.simtaa_erp.activity.Activity_Add_Enquiry;
import com.example.banyan.simtaa_erp.activity.Activity_Enquiry_Description;
import com.example.banyan.simtaa_erp.adapter.Adapter_Enquiry_List;
import com.example.banyan.simtaa_erp.global.App_Config;
import com.example.banyan.simtaa_erp.global.Session_Manager;
import com.sdsmdg.tastytoast.TastyToast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import dmax.dialog.SpotsDialog;
import static com.willy.ratingbar.BaseRatingBar.TAG;
public class Fragment_Enquiry_List extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
public Fragment_Enquiry_List() {
}
private FloatingActionButton fab_enquiry;
String str_user_name, str_user_id,str_select_task_id;
private ProgressDialog pDialog;
private SpotsDialog dialog_load_more;
public static RequestQueue queue;
Session_Manager session;
private SwipeRefreshLayout enquiry_list_swipe_refresh_layout;
private ListView enquiry_listView;
public static final String TAG_ID= "id";
public static final String TAG_CUSTOMER_ID = "cus_id";
public static final String TAG_IMAGE_ENQUIRY = "image";
public static final String TAG_DESCRIPTION = "description";
public static final String TAG_DATE_ENQUIRY = "date";
public static final String TAG_PROJECT_STATUS = "project_status";
public static final String TAG_CREATED_USERID = "created_userid";
public static final String TAG_CREATED_USERROLE = "created_userrole";
public static final String TAG_CREATED_DATETIME = "created_datetime";
public static final String TAG_CUSTOMER_DETAILS = "customer_details";
int int_starting_item_no = 0, int_last_item_no = 0, int_load_more_count = 100;
public Adapter_Enquiry_List Adapter;
static ArrayList<HashMap<String, String>> enquiry_list;
HashMap<String, String> params = new HashMap<String, String>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_enquiry_list, container, false);
session = new Session_Manager(getActivity());
session.checkLogin();
HashMap<String, String> user = session.getUserDetails();
str_user_id = user.get(Session_Manager.KEY_USER_ID);
str_user_name = user.get(Session_Manager.KEY_USER_NAME);
System.out.println("USER ID from Session ::::" + str_user_id);
System.out.println("USER NAME from Session ::::" + str_user_name);
enquiry_listView = (ListView) rootView.findViewById(R.id.list_enquiry_list);
fab_enquiry = (FloatingActionButton) rootView.findViewById(R.id.fab_enquiry);
enquiry_list_swipe_refresh_layout = (SwipeRefreshLayout) rootView.findViewById(R.id.enquiry_list_swipe_refresh_layout);
enquiry_list_swipe_refresh_layout.setOnRefreshListener(this);
enquiry_list = new ArrayList<HashMap<String, String>>()
enquiry_list_swipe_refresh_layout.post(new Runnable() {
#Override
public void run() {
try {
enquiry_list_swipe_refresh_layout.setRefreshing(true);
queue = Volley.newRequestQueue(getActivity().getApplicationContext());
Activity_Get_Enquiry_List(int_starting_item_no, int_load_more_count);
} catch (Exception e) {
}
}
});
enquiry_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
System.out.println("Event Trigered by Item" );
String str_enquiry_id = enquiry_list.get(position).get(TAG_ID);
String str_customer_id = enquiry_list.get(position).get(TAG_CUSTOMER_ID);
String str_image_enquiry = enquiry_list.get(position).get(TAG_IMAGE_ENQUIRY);
String str_description_enquiry = enquiry_list.get(position).get(TAG_DESCRIPTION);
String str_date_enquiry = enquiry_list.get(position).get(TAG_DATE_ENQUIRY);
String str_project_status = enquiry_list.get(position).get(TAG_PROJECT_STATUS);
String str_created_userid = enquiry_list.get(position).get(TAG_CREATED_USERID);
String str_created_userrole = enquiry_list.get(position).get(TAG_CREATED_USERROLE);
String str_created_datetime = enquiry_list.get(position).get(TAG_CREATED_DATETIME);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("enquiry_id", str_enquiry_id);
editor.putString("customer_id", str_customer_id);
editor.putString("image_enquiry", str_image_enquiry);
editor.putString("description_enquiry", str_description_enquiry);
editor.putString("date_enquiry", str_date_enquiry);
editor.putString("project_status", str_project_status);
editor.putString("created_userid", str_created_userid);
editor.putString("created_role", str_created_userrole);
editor.putString("created_datetime", str_created_datetime);
editor.commit();
Intent i = new Intent(getContext(),Activity_Enquiry_Description.class);
startActivity(i);
}
});
enquiry_listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int pos, long id) {
// TODO Auto-generated method stub
str_select_task_id = enquiry_list.get(pos).get(TAG_ID);
Delete_Task_alert();
return true;
}
});
return rootView;
}
private void Activity_Get_Enquiry_List(final int int_starting_item_no, final int int_load_more_count) {
StringRequest request = new StringRequest(Request.Method.POST, App_Config.url_list_enquiry, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG_CUSTOMER_DETAILS, response.toString());
Log.d("TAG_ENQUIRY_LIST", response.toString());
try {
JSONObject obj = new JSONObject(response);
System.out.println("REG 00" + obj);
int success = obj.getInt("success");
System.out.println("REG" + success);
if (success == 1) {
JSONArray enquiry = obj.getJSONArray("Enquiry");
for (int i = 0; enquiry.length() > i; i++) {
JSONObject obj_one = enquiry.getJSONObject(i);
String str_enquiry_id = obj_one.getString(TAG_ID);
String str_customer_id = obj_one.getString(TAG_CUSTOMER_ID);
String str_image_enquiry = obj_one.getString(TAG_IMAGE_ENQUIRY);
String str_description_enquiry = obj_one.getString(TAG_DESCRIPTION);
String str_date_enquiry = obj_one.getString(TAG_DATE_ENQUIRY);
String str_project_status = obj_one.getString(TAG_PROJECT_STATUS);
String str_created_userid = obj_one.getString(TAG_CREATED_USERID);
String str_created_userrole = obj_one.getString(TAG_CREATED_USERROLE);
String str_created_datetime = obj_one.getString(TAG_CREATED_DATETIME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, str_enquiry_id);
map.put(TAG_CUSTOMER_ID, str_customer_id);
map.put(TAG_IMAGE_ENQUIRY, str_image_enquiry);
map.put(TAG_DESCRIPTION, str_description_enquiry);
map.put(TAG_DATE_ENQUIRY, str_date_enquiry);
map.put(TAG_PROJECT_STATUS, str_project_status);
map.put(TAG_CREATED_USERID, str_created_userid);
map.put(TAG_CREATED_USERROLE, str_created_userrole);
map.put(TAG_CREATED_DATETIME, str_created_datetime);
enquiry_list.add(map);
System.out.println("HASHMAP ARRAY" + enquiry_list);
}
Adapter = new Adapter_Enquiry_List(getActivity(), enquiry_list);
enquiry_listView.setAdapter(Adapter);
enquiry_list_swipe_refresh_layout.setRefreshing(false);
} else {
TastyToast.makeText(getContext(), "OOPS FAILED TO LOAD", TastyToast.LENGTH_LONG, TastyToast.WARNING);
}
LoadMoreButtonVisible();
enquiry_list_swipe_refresh_layout.setRefreshing(false);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
enquiry_list_swipe_refresh_layout.setRefreshing(false);
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", str_user_id);
params.put("start",""+ int_starting_item_no);
params.put("limit",""+ int_load_more_count);
System.out.println("user_id " + str_user_id);
System.out.println("start " + int_starting_item_no);
System.out.println("limit " + int_load_more_count);
return params;
}
};
queue.add(request);
}
}
If there are clickable UI elements like Button, Imagebutton are present in child view of list/Recyclerview, they can take control of click events. So, Recyclerview would not get chance to click event.
Please set android:focusable="false" for all child clickable view. Then your itemclick will work.
You can also use following property in parent view that prevent child view getting focus.
android:descendantFocusability="blocksDescendants"
You implement wrong method of list item click listener, just replace this
enquiry_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
}
To:
enquiry_listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {}}
I would like to put 2 columns of recyclerview every row.
Right now my design is like this:
and i would like to put 2 so the scroll is not to long.
I have this view inside a fragment and I use a recyclerview adapter but I have no clue how to tell it to use its parent with, so it can fill the width of the screen. In the fragment I recive a JSON from an online database using an AsyncTask and fill in the recyclerview on the onPostExecute of the AsyncTask.
If anyone has any Idea how i can do it, I can't seem to find this anywhere
Thx!
My recyclerview Adapter:
package com.example.juanfri.seguridadmainactivity;
/**
* Created by jlira on 30/05/2017.
*/
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
/**
* Created by Juanfri on 29/05/2017.
*/
public class RecyclerAdapterSerie extends RecyclerView.Adapter<RecyclerAdapterSerie.SerieHolder> {
private ArrayList<Serie> mSerie;
#Override
public RecyclerAdapterSerie.SerieHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View inflatedView = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.recyclerview_card, viewGroup, false);
return new SerieHolder(inflatedView);
}
#Override
public void onBindViewHolder(RecyclerAdapterSerie.SerieHolder holder, int i) {
Serie itemPhoto = mSerie.get(i);
holder.bindPhoto(itemPhoto);
}
#Override
public int getItemCount() {
return mSerie.size();
}
public RecyclerAdapterSerie(ArrayList<Serie> serie) {
mSerie = serie;
}
public static class SerieHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
//2
private ImageView mItemImage;
private TextView mItemDate;
private TextView mItemDescription;
private Serie serie;
//3
private static final String PHOTO_KEY = "PHOTO";
//4
public SerieHolder(View v) {
super(v);
mItemImage = (ImageView) v.findViewById(R.id.item_image);
mItemDate = (TextView) v.findViewById(R.id.item_date);
mItemDescription = (TextView) v.findViewById(R.id.item_description);
v.setOnClickListener(this);
}
//5
#Override
public void onClick(View v) {
/*Context context = itemView.getContext();
Intent showPhotoIntent = new Intent(context, Pelicula.class);
showPhotoIntent.putExtra(PHOTO_KEY, peli);
context.startActivity(showPhotoIntent);*/
}
public void bindPhoto(Serie mserie) {
serie = mserie;
String Nombre = mserie.getNombreSerie();
if(Nombre.length() >= 25)
{
Nombre = Nombre.substring(0,22);
Nombre = Nombre + "...";
}
Picasso.with(mItemImage.getContext()).load(mserie.getPoster()).into(mItemImage);
mItemDate.setText(Nombre);
mItemDescription.setText(Integer.toString(mserie.getIdTMDB()));
}
}
}
My fragment (where i create the recyclerview)
package com.example.juanfri.seguridadmainactivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import static android.content.ContentValues.TAG;
/**
* Created by jlira on 06/06/2017.
*/
public class FragmentoSeriesPelis extends Fragment {
public final String API = "5e2780b2117b40f9e4dfb96572a7bc4d";
public final String URLFOTO ="https://image.tmdb.org/t/p/original/";
private ProgressDialog pDialog;
private RecyclerView recyclerView;
private LinearLayoutManager mLinearLayoutManager;
private ArrayList<Serie> series;
private ArrayList<Pelicula> Pelis;
private RecyclerAdapterSerie mAdapterSerie;
private RecyclerAdapterPelicula mAdapterPeli;
private int pagina;
private String url;
private Button CargarMas;
private String tipo;
private int MaxPag;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.series_pelis_layout, container, false);
view.setTag(TAG);
Bundle args = getArguments();
series = new ArrayList<>();
Pelis = new ArrayList<>();
MaxPag = 2;
pagina = args.getInt("Page");
url = args.getString("url");
tipo = args.getString("Tipo");
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerViewSerieshoy);
//mLinearLayoutManagerSerie = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
//recyclerViewSerie.setLayoutManager(mLinearLayoutManagerSerie);
//mAdapterSerie = new RecyclerAdapterSerie(seriesHoy);
//recyclerViewSerie.setAdapter(mAdapterSerie);
new GetSeriesHoy().execute();
CargarMas = (Button) view.findViewById(R.id.buttonCargarMas);
CargarMas.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(pagina+1<=MaxPag)
{
pagina++;
new GetSeriesHoy().execute();
}
else
{
Toast.makeText(getActivity(), "No hay mas resultados", Toast.LENGTH_LONG).show();
}
}
});
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Series de Hoy");
}
private class GetSeriesHoy extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
//url = "https://api.themoviedb.org/3/tv/airing_today?api_key="+API+"&language=en-US&page="+pagina;
String aux = url+pagina;
String jsonStr = sh.makeServiceCall(aux);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
MaxPag = jsonObj.getInt("total_pages");
JSONArray contacts = jsonObj.getJSONArray("results");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
int IdSerie = i;
int idTMDB = c.getInt("id");
String nombreSerie;
String poster =URLFOTO + c.getString("poster_path");
if(tipo.equalsIgnoreCase("Series"))
{
nombreSerie = c.getString("name");
Serie nuevo = new Serie();
nuevo.setIdSerie(IdSerie);
nuevo.setNombreSerie(nombreSerie);
nuevo.setIdTMDB(idTMDB);
nuevo.setPoster(poster);
series.add(nuevo);
}
else
{
nombreSerie = c.getString("title");
Pelicula nuevo = new Pelicula();
nuevo.setIdPelicula(IdSerie);
nuevo.setNombrePelicula(nombreSerie);
nuevo.setIdTMDB(idTMDB);
nuevo.setPoster(poster);
Pelis.add(nuevo);
}
}
} catch (final JSONException e) {
Toast.makeText(getActivity(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
} else {
Toast.makeText(getActivity(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
//Aqui Realizar la RecycleView BuildUp
if(tipo.equalsIgnoreCase("Series"))
{
mLinearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(mLinearLayoutManager);
mAdapterSerie = new RecyclerAdapterSerie(series);
recyclerView.setAdapter(mAdapterSerie);
}else
{
mLinearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(mLinearLayoutManager);
mAdapterPeli = new RecyclerAdapterPelicula(Pelis);
recyclerView.setAdapter(mAdapterPeli);
}
}
}
}
Replace your LinearLayoutManager for a GridLayoutManager like this:
private GridLayoutManager mGridLayoutManager;
// ...
mGridLayoutManager = new GridLayoutManager(getActivity(), 2);
Then you can use it the same way as the LinearLayoutManager.
My Fragment is not showing custom listview data. Asynctask is working properly but after sometime application is crashing with null pointer exception.
My fragment class code :
package com.example.y34h1a.androidlime.Fragment;
import android.app.ProgressDialog;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.example.y34h1a.androidlime.R;
import com.example.y34h1a.androidlime.adapter.FeedListAdapter;
import com.example.y34h1a.androidlime.data.FeedItem;
import com.example.y34h1a.androidlime.network.VolleySigleton;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
public class FragmentBoxOffice extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private VolleySigleton volleySigleton;
private ImageLoader imageLoader;
private RequestQueue requestQueue;
private OnFragmentInteractionListener mListener;
private static final String TAG = FragmentBoxOffice.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private ArrayList<FeedItem> feedItems;
private String URL_FEED = "http://androidlime.com/wp-json/posts";
private FeedItem feedItem = new FeedItem();
// TODO: Rename and change types and number of parameters
public static FragmentBoxOffice newInstance(String param1, String param2) {
FragmentBoxOffice fragment = new FragmentBoxOffice();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public FragmentBoxOffice() {
// Required empty public constructor
feedItems = new ArrayList<FeedItem>();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_box_office, container, false);
listView = (ListView) view.findViewById(R.id.fragmentList);
new JSONAsyncTask().execute(URL_FEED);
return view;
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(getActivity());
dialog.setMessage("Loading...");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
for(String url : urls){
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONArray jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject titleObj = jsonArray.getJSONObject(i);
String title = titleObj.getString("title");
feedItem.setStatus(title);
Log.i("arif", title);
//DATE
String date = titleObj.getString("date");
feedItem.setTimeStamp(date);
Log.i("arif", date);
//Author Name
JSONObject author = titleObj.getJSONObject("author");
String name = author.getString("name");
feedItem.setName(name);
Log.i("arif", name);
//Author Profile Pic
String profilePic = author.getString("avatar");
feedItem.setProfilePic(profilePic);
Log.i("arif", profilePic);
//Post thumbnail
JSONObject thumnailObj = titleObj.getJSONObject("featured_image");
String thumbnail = thumnailObj.getString("guid");
feedItem.setThumnail(thumbnail);
Log.i("arif", thumbnail);
feedItems.add(feedItem);
}
return true;
//------------------>>
} catch (IOException e) {
Log.e("arif", "Parse Exception");
} catch (JSONException e) {
Log.e("arif", "Parse Exception");
}
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
listAdapter = new FeedListAdapter(getActivity().getApplicationContext(),R.layout.feed_item,feedItems);
listView.setAdapter(listAdapter);
if(result == false)
Log.i("arif","unable to featch data");
}
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
}
My Custom Adapter Class:
package com.example.y34h1a.androidlime.adapter;
import android.app.Activity;
import android.content.Context;
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.example.y34h1a.androidlime.R;
import com.example.y34h1a.androidlime.data.FeedItem;
import java.util.ArrayList;
import java.util.List;
public class FeedListAdapter extends ArrayAdapter<FeedItem> {
private LayoutInflater vi;
private List<FeedItem> feedItems;
int Resource;
ViewHolder holder;
public FeedListAdapter(Context context, int resource, ArrayList<FeedItem> feedItems) {
super(context, resource, feedItems);
this.feedItems = feedItems;
Resource = resource;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// convert view = design
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = ((Activity)getContext()).getLayoutInflater().inflate(R.layout.feed_item,null);
holder.name = (TextView) v.findViewById(R.id.name);
holder.status = (TextView) v.findViewById(R.id.txtStatusMsg);
holder.time = (TextView) v.findViewById(R.id.timestamp);
holder.url = (TextView) v.findViewById(R.id.txtUrl);
holder.profilePic = (ImageView) v.findViewById(R.id.profilePic);
holder.thumbnail = (ImageView) v.findViewById(R.id.thumbernail);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
v.setTag(holder);
holder.name.setText(feedItems.get(position).getName());
holder.status.setText(feedItems.get(position).getStatus());
holder.time.setText(feedItems.get(position).getTimeStamp());
holder.url.setText(feedItems.get(position).getUrl());
holder.profilePic.setImageResource(R.drawable.ic_launcher);
holder.profilePic.setImageResource(R.drawable.sample);
return v;
}
static class ViewHolder {
public TextView name;
public TextView status;
public TextView url;
public TextView time;
public ImageView profilePic;
public ImageView thumbnail;
}
}
The line where error showing is :
View v = ((Activity)getContext()).getLayoutInflater().inflate(R.layout.feed_item,null);'
From your code, I think your error is more like ClassCastException, don't know why it's NPE, because
listAdapter = new FeedListAdapter(getActivity().getApplicationContext(),R.layout.feed_item,feedItems);
You pass a ApplicationContext then cast it to a Activity
v = ((Activity)getContext()).getLayoutInflater().inflate(R.layout.feed_item,null);
Try this may works:
in onPostExecute:
if (getActivity() != null) {
listAdapter = new FeedListAdapter(getActivity().getApplicationContext(),R.layout.feed_item,feedItems);
listView.setAdapter(listAdapter);
}
in getView:
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.feed_item, parent, false);
Try:
v = (LayoutInflater.from(getContext()).inflate(R.layout.feed_item, parent, false);
I have a web service for search in some videos by name.
It pass me the names and images of the videos.
how should I say which image is for which video?
and how shoud i say it to play
package com.video;
import java.util.List;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import com.uvideo.adapter.VideoSearchAdapter;
import com.uvideo.controller.MasterVideoController;
import com.uvideo.model.VideoSearch;
public class ActivityVideoSearch extends Activity implements OnClickListener {
private VideoSearchAdapter videoSearchAdapter;
private GridView grdVideoList;
private List<VideoSearch> listVideo;
private EditText edtKeySearch;
private Button btnSearch;
// -------------------------
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_activity_video_search);
ini();
}
// -------------------------
private void ini() {
grdVideoList = (GridView) findViewById(R.id.grdVideoList);
edtKeySearch = (EditText) findViewById(R.id.edtKeySearch);
btnSearch = (Button) findViewById(R.id.btnSearchVideo);
btnSearch.setOnClickListener(this);
}
// -------------------------
private class SearchVideo extends AsyncTask<String, Void, List<VideoSearch>>{
#Override
protected List<VideoSearch> doInBackground(String... params) {
MasterVideoController masterVideoController = new MasterVideoController();
return masterVideoController.searchVideo(params[0]);
}
#Override
protected void onPostExecute(List<VideoSearch> result) {
super.onPostExecute(result);
listVideo = result;
videoSearchAdapter = new VideoSearchAdapter(getBaseContext(),result);
grdVideoList.setAdapter(videoSearchAdapter);
}
}
// -------------------------
#Override
public void onClick(View v) {
new SearchVideo().execute(edtKeySearch.getText().toString());
}
}
package com.video.adapter;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.uvideo.R;
import com.uvideo.model.VideoSearch;
public class VideoSearchAdapter extends ArrayAdapter {
private List<VideoSearch> listVideo;
private Context context;
// ---------------------
public VideoSearchAdapter(Context context,List<VideoSearch> listVideo) {
super(context, R.layout.row_video_item, listVideo);
this .listVideo = listVideo;
this.context = context;
}
// ---------------------
#Override
public int getCount() {
return super.getCount();
}
// ---------------------
#Override
public VideoSearch getItem(int position) {
return ((listVideo!=null ? listVideo.get(position):null));
}
// ---------------------
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if(view==null){
LayoutInflater inflater=(LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.row_video_item, parent,false);
}
final VideoSearch video=listVideo.get(position);
if(video!=null){
TextView txtMusicName = (TextView) view.findViewById(R.id.txtVideoName);
txtMusicName.setTextSize(16);
txtMusicName.setText(video.getVideoTitle());
// ---------------------
}
return view;
}
// ---------------------
#Override
public long getItemId(int position) {
return position;
}
}
package com.video.controller;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import com.uvideo.model.VideoDetail;
import com.uvideo.model.VideoSearch;
import com.uvideo.tools.parser.XmlParser;
import com.uvideo.tools.webservice.WebServiceConnection;
import com.uvideo.tools.webservice.WebServiceConnection2;
public class MasterVideoController extends WebServiceConnection {
private String result;
private JSONObject jsonObject;
private JSONArray jsonObjectArray;
private final static String SEARCHKEY="SearchKey";
// -------------------------
public MasterVideoController() {
}
// -------------------------
public List<VideoDetail> getVideoList(){
List<NameValuePair> params = new ArrayList<NameValuePair>();
result = super.sendRequest("MasterVideo", params);
return getVideoListJson(result);
}
// -------------------------
private List<VideoDetail> getVideoListJson(String json){
List<VideoDetail> listVideo = new ArrayList<VideoDetail>();
json = new XmlParser().getxml(json);
try{
jsonObject = new JSONObject(json);
listVideo.add(new VideoDetail(jsonObject.optString(VideoDetail.VIDEOTITLE)
, jsonObject.optString(VideoDetail.VIDEOPATH)
, jsonObject.optString(VideoDetail.VIDEOIMAGE)
, jsonObject.optInt(VideoDetail.VIDEOVISIT)
, jsonObject.optString(VideoDetail.CHANNELNAME)
, jsonObject.optString(VideoDetail.USERNAME)
, jsonObject.optString(VideoDetail.USERIMAGE)
, jsonObject.optInt(VideoDetail.USERVIDEOCOUNT)
, jsonObject.optInt(VideoDetail.USERFOLLOWER)));
//}
return listVideo;
}
catch(Exception exp){
}
return null;
}
// -------------------------
public List<VideoSearch> searchVideo(String requestSearchKey){
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(SEARCHKEY,requestSearchKey));
result = super.sendRequest("SearchByVideoTitle", params);
return getVideoListSearchJson(result);
}
// -------------------------
private List<VideoSearch> getVideoListSearchJson(String json){
List<VideoSearch> listVideo = new ArrayList<VideoSearch>();
json = new XmlParser().getxml(json);
try{
jsonObjectArray = new JSONArray(json);
for (int i = 0; i < jsonObjectArray.length(); i++) {
jsonObject = (JSONObject) jsonObjectArray.get(i);
listVideo.add(new VideoSearch(jsonObject.optString(VideoSearch.VIDEOTITLE)
, jsonObject.optString(VideoSearch.VIDEOPATH)
, jsonObject.optString(VideoSearch.VIDEOIMAGE)
, jsonObject.optInt(VideoSearch.VIDEOVISIT)
, jsonObject.optString(VideoSearch.USERNAME)));
}
return listVideo;
}
catch(Exception exp){
String a = "";
}
return null;
}
// -------------------------
}
package com.video.model;
public class VideoSearch {
// -------------------------
public final static String VIDEOTITLE="VideoTitle";
public final static String VIDEOPATH="VideoPath";
public final static String VIDEOIMAGE="VideoImage";
public final static String VIDEOVISIT="VideoVisit";
public final static String USERNAME="UserName";
// -------------------------
private String videoTitle ;
private String videoPath ;
private String videoImage ;
private int videoVisit ;
private String username ;
// -------------------------
public VideoSearch(String videoTitle , String videoPath ,String videoImage ,int
videoVisit , String username) {
this.videoTitle = videoTitle;
this.videoPath = videoPath;
this.videoImage = videoImage;
this.videoVisit = videoVisit;
this.username = username;
}
// -------------------------
public VideoSearch() {
}
// -------------------------
public String getVideoTitle(){
return videoTitle;
}
public String getvideoPath(){
return videoPath;
}
public String getVideoImage(){
return videoImage;
}
public int getVideoVisit(){
return videoVisit;
}
public String getUsername(){
return username;
}
// -------------------------
public void setVideoTitle(String videoTitle){
this.videoTitle = videoTitle;
}
public void setvideoPath(String videoPath){
this.videoPath = videoPath;
}
public void setVideoImage(String videoImage){
this.videoImage = videoImage;
}
public void setVideoVisit(int videoVisit){
this.videoVisit = videoVisit;
}
public void setUsername(String username){
this.username = username;
}
// -------------------------
}
Firstly, your not clearly stated.
If you are using web service, then you should send the items by coupling them in web service.
Like in JSON
{
video[{"name":"abc","image_url":"kvndskk"}{"name":"abc","image_url":"kvndskk"}{"name":"abc","image_url":"kvndskk"}{"name":"abc","image_url":"kvndskk"}
]
}
here you see you receiving in couple
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.