我正在使用Web域解析数据并将其传递给我的android listview。我怎样才能在第一次运行时加载数据,所以当我再次点击选项卡时,它将不会再次加载来自网络的数据并且列表视图将被填充?有可能吗?
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();
}
}
}
答案 0 :(得分:1)
创建此变量
boolean isDataLoaded = false;
你的onPageSelected方法是:
@Override
public void onPageSelected(int position) {
if(position==0){
if(!isDataLoaded)
new LoadProducts().execute();
}
}
在LoadProducts Asynctask的PostExecute中正确填充listview时,将变量isDataLoaded更新为true:
updateproductlist();
isDataLoaded = true;
或者在您的方法updateproductlist中,您可以决定