Display image in imageview by SimpleAdapter - android

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

Related

how to use notifyDataSetAdapter in listview android?

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);
}

LinkedHashMap error in SimpleAdapter

I've an error in my simpleAdapter on 'map' and can't resolve it. I've created a LinkedHashMap through a json file.
See screenshot below. I assume it's correct. This screenshot is only for seeing the content of the array.
See my code below:
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
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.LinkedHashMap;
public class BlogFragment extends Fragment {
View myView;
ArrayList<String> lists = new ArrayList<>();
ListView lv = (ListView) myView.findViewById(R.id.listView);
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.blog_layout, container, false);
new AsyncTaskParseJson().execute();
return myView;
}
public class AsyncTaskParseJson extends AsyncTask<LinkedHashMap, LinkedHashMap, LinkedHashMap> {
String url = "myUrl"; // Link to json file
JSONArray dataJsonArr = null;
ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(getActivity(), "", "Loading blog ...");
}
#Override
protected LinkedHashMap<Integer, ArrayList<String>> doInBackground(LinkedHashMap... params) {
LinkedHashMap<Integer, ArrayList<String>> map = new LinkedHashMap<>();
try {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);
dataJsonArr = json.getJSONArray("blog");
for (int i = dataJsonArr.length()-1; i >= 0 ; i--) {
JSONObject c = dataJsonArr.getJSONObject(i);
String afb = c.getString("afbeelding");
String tt = c.getString("titel");
String inh = c.getString("inhoud");
lists = new ArrayList<>();
lists.add(tt);
lists.add(afb);
lists.add(inh);
map.put(i,lists);
}
} catch (JSONException e) {
e.printStackTrace();
}
return map;
}
#Override
protected void onPostExecute(LinkedHashMap map) {
dialog.dismiss();
String[] from = new String[]{"6", "5", "4", "3", "2", "1"};
int[] to = new int[]{R.id.textView, R.id.textView2, R.id.textView3};
//Map<String, ArrayList<String>> map1 = new LinkedHashMap<>(map);
SimpleAdapter simpleAdapter;
simpleAdapter = new SimpleAdapter(getActivity(), map, R.layout.blog_layout, from, to); // <<< **I get an error on 'map'**
lv.setAdapter(simpleAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(getActivity(), Detail.class);
i.putExtra("string", Long.toString(id));
startActivity(i);
}
});
}}}
I already tried to convert LinkedHashMap to Map but it didn't resolve the issue.
Can someone help me, please?
Thank you!

How to load json parsed data only on first run so when i click the tab the listview already populated?

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

When change setContentView

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

AsyncTask is not functioning on my second fragment connected to Mysql database on swipe

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.

Categories

Resources