Java 向ArrayList追加新数据的简单方法
我正在制作一个应用程序,显示来自Java 向ArrayList追加新数据的简单方法,java,android,eclipse,android-asynctask,append,Java,Android,Eclipse,Android Asynctask,Append,我正在制作一个应用程序,显示来自Tumblr帐户的图像。它加载前20项,然后在底部有一个“加载更多”按钮。单击“加载更多”按钮时,我使用AsyncTask来处理它。我已经按照我认为应该的方式设置了所有内容,但是我没有将接下来的20幅图像添加到列表中。我见过其他一些项目使用自定义的listAdapter类,但我正在寻找一种更简单的方法 这是我的密码: public class Example extends Activity { Context context = null; ListView
Tumblr
帐户的图像。它加载前20项,然后在底部有一个“加载更多”按钮。单击“加载更多”按钮时,我使用AsyncTask
来处理它。我已经按照我认为应该的方式设置了所有内容,但是我没有将接下来的20幅图像添加到列表中。我见过其他一些项目使用自定义的listAdapter
类,但我正在寻找一种更简单的方法
这是我的密码:
public class Example extends Activity {
Context context = null;
ListView listView = null;
TextView footer;
int offset = 0;
ProgressDialog pDialog;
private String searchUrl = "http://api.tumblr.com/v2/blog/factsandchicks.com/posts?api_key=API_KEY&offset=0";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<Tumblr> tumblrs;
try {
tumblrs = getTumblrs();
listView = (ListView) findViewById(R.id.list);
View v = getLayoutInflater().inflate(R.layout.footer_layout, null);
footer = (TextView) v.findViewById(R.id.tvFoot);
listView.addFooterView(v);
listView.setAdapter(new UserItemAdapter(this, R.layout.listitem,
tumblrs));
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
footer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new loadMoreListView().execute();
}
});
}
public class UserItemAdapter extends ArrayAdapter<Tumblr> {
private ArrayList<Tumblr> tumblrs;
public UserItemAdapter(Context context, int imageViewResourceId,
ArrayList<Tumblr> tumblrs) {
super(context, imageViewResourceId, tumblrs);
this.tumblrs = tumblrs;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.listitem, null);
}
Tumblr tumblr = tumblrs.get(position);
if (tumblr != null) {
ImageView image = (ImageView) v.findViewById(R.id.avatar);
if (image != null) {
image.setImageBitmap(getBitmap(tumblr.image_url));
}
}
return v;
}
}
public Bitmap getBitmap(String bitmapUrl) {
try {
URL url = new URL(bitmapUrl);
return BitmapFactory.decodeStream(url.openConnection()
.getInputStream());
} catch (Exception ex) {
return null;
}
}
public ArrayList<Tumblr> getTumblrs() throws ClientProtocolException,
IOException, JSONException {
searchUrl = "http://api.tumblr.com/v2/blog/factsandchicks.com/posts?api_key=API_KEY&offset=0";
ArrayList<Tumblr> tumblrs = new ArrayList<Tumblr>();
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(searchUrl);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = null;
try {
responseBody = client.execute(get, responseHandler);
} catch (Exception ex) {
ex.printStackTrace();
}
JSONObject jsonObject = new JSONObject(responseBody);
JSONArray posts = jsonObject.getJSONObject("response").getJSONArray(
"posts");
for (int i = 0; i < posts.length(); i++) {
JSONArray photos = posts.getJSONObject(i).getJSONArray("photos");
for (int j = 0; j < photos.length(); j++) {
JSONObject photo = photos.getJSONObject(j);
String url = photo.getJSONArray("alt_sizes").getJSONObject(0)
.getString("url");
Tumblr tumblr = new Tumblr(url);
tumblrs.add(tumblr);
}
}
return tumblrs;
}
public class Tumblr {
public String image_url;
public Tumblr(String url) {
this.image_url = url;
}
}
private class loadMoreListView extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
// Showing progress dialog before sending http request
pDialog = new ProgressDialog(Example.this);
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... unused) {
// TODO Auto-generated method stub
runOnUiThread(new Runnable() {
public void run() {
// increment current page
offset += 20;
// Next page request
searchUrl = "http://api.tumblr.com/v2/blog/factsandchicks.com/posts?api_key=API_KEY&offset="
+ offset;
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(searchUrl);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = null;
try {
responseBody = client.execute(get, responseHandler);
} catch (Exception ex) {
ex.printStackTrace();
}
JSONObject jsonObject;
try {
jsonObject = new JSONObject(responseBody);
JSONArray posts = jsonObject.getJSONObject("response")
.getJSONArray("posts");
for (int i = 0; i < posts.length(); i++) {
JSONArray photos = posts.getJSONObject(i)
.getJSONArray("photos");
for (int j = 0; j < photos.length(); j++) {
JSONObject photo = photos.getJSONObject(j);
String url = photo.getJSONArray("alt_sizes")
.getJSONObject(0).getString("url");
Tumblr tumblr = new Tumblr(url);
tumblrs.add(tumblr);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// get listview current position - used to maintain scroll
// position
int currentPosition = listView.getFirstVisiblePosition();
// Appending new data to tumblrs ArrayList
// Setting new scroll position
listView.setSelectionFromTop(currentPosition + 1, 0);
}
});
return null;
}
protected void onPostExecute(Void unused) {
pDialog.dismiss();
}
}
}
公共类示例扩展活动{
Context=null;
ListView ListView=null;
文本视图页脚;
整数偏移=0;
ProgressDialog;
专用字符串searchUrl=”http://api.tumblr.com/v2/blog/factsandchicks.com/posts?api_key=API_KEY&offset=0";
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList tumblrs;
试一试{
tumblrs=getTumblrs();
listView=(listView)findViewById(R.id.list);
视图v=GetLayoutFlater()。充气(R.layout.footer\u布局,null);
页脚=(TextView)v.findViewById(R.id.tvFoot);
listView.addFooterView(v);
setAdapter(新的UserItemAdapter(这个,R.layout.listitem,
tumblrs);
}捕获(客户端协议例外e){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}捕获(JSONException e){
e、 printStackTrace();
}
footer.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
新建loadMoreListView().execute();
}
});
}
公共类UserItemAdapter扩展了ArrayAdapter{
私人ArrayList tumblrs;
公共UserItemAdapter(上下文上下文,int-imageViewResourceId,
ArrayList tumblrs){
super(上下文、imageViewResourceId、tumblrs);
this.tumblrs=tumblrs;
}
@凌驾
公共视图getView(int位置、视图转换视图、视图组父视图){
视图v=转换视图;
如果(v==null){
LayoutInflater vi=(LayoutInflater)getSystemService(Context.LAYOUT\u INFLATER\u SERVICE);
v=vi.充气(R.layout.listitem,空);
}
Tumblr Tumblr=tumblrs.get(位置);
如果(tumblr!=null){
ImageView图像=(ImageView)v.findViewById(R.id.avatar);
如果(图像!=null){
setImageBitmap(getBitmap(tumblr.image_url));
}
}
返回v;
}
}
公共位图getBitmap(字符串bitmapUrl){
试一试{
URL URL=新URL(位图URL);
返回BitmapFactory.decodeStream(url.openConnection()
.getInputStream());
}捕获(例外情况除外){
返回null;
}
}
public ArrayList getTumblrs()抛出ClientProtocolException,
IOException,jsoneexception{
搜索URL=”http://api.tumblr.com/v2/blog/factsandchicks.com/posts?api_key=API_KEY&offset=0";
ArrayList tumblrs=新的ArrayList();
HttpClient=new DefaultHttpClient();
HttpGet=newhttpget(searchUrl);
ResponseHandler ResponseHandler=新BasicResponseHandler();
字符串responseBody=null;
试一试{
responseBody=client.execute(get,responseHandler);
}捕获(例外情况除外){
例如printStackTrace();
}
JSONObject JSONObject=新的JSONObject(ResponseBy);
JSONArray posts=jsonObject.getJSONObject(“响应”).getJSONArray(
“员额”);
对于(int i=0;ipublic class ProductAdapter extends ArrayAdapter<ProductListPojo> {
Activity a;
Context context;
int layoutResourceId;
ArrayList<ProductListPojo> plp = null;
ImageLoader iLoader;
public YoutubeImageLoader imageLoader;
public ProductAdapter(Context context, int resource, ArrayList<ProductListPojo> listy) {
super(context, resource, listy);
this.layoutResourceId = resource;
this.context = context;
this.plp = listy;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
iLoader = new ImageLoader(context);
WeatherHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
imageLoader = new YoutubeImageLoader(context);
holder = new WeatherHolder();
holder.imgIcon = (ImageView)row.findViewById(R.id.imageView_PrefImage);
holder.imgIsPreffered = (ImageView)row.findViewById(R.id.imageView_isPreffered);
holder.txtTitle = (TextView)row.findViewById(R.id.textView_HeadingPref);
holder.txtprovider = (TextView)row.findViewById(R.id.textView_Provider);
holder.counterParty = (TextView)row.findViewById(R.id.textView_counterparty);
holder.closingDate = (TextView)row.findViewById(R.id.textView_ClosingDate);
holder.term = (TextView)row.findViewById(R.id.textView_Term);
holder.indexLink = (TextView)row.findViewById(R.id.textView_IndexLink);
holder.investmentType = (TextView)row.findViewById(R.id.textView_InvestmentType);
holder.productType = (TextView)row.findViewById(R.id.textView_ProductType);
holder.li = (LinearLayout)row.findViewById(R.id.linearLayout_IsPreferred);
row.setTag(holder);
}
else
{
holder = (WeatherHolder)row.getTag();
}
ProductListPojo product = plp.get(position);
try{
holder.imgIcon.setTag(product.getpId());
imageLoader.DisplayImage("http://www.xxxxxxxx.com/Resources/Covers/FullSize/"+product.getpId()+"."+"jpg", a, holder.imgIcon);
}catch(Exception ex){
holder.imgIcon.setImageResource(R.drawable.milkywhite);
}
holder.imgIsPreffered.setBackgroundResource(R.drawable.correct);
if (product.isPref()){
//holder.imgIsPreffered.setVisibility(View.VISIBLE);
holder.li.setVisibility(View.VISIBLE);
}else{
//holder.imgIsPreffered.setVisibility(View.INVISIBLE);
holder.li.setVisibility(View.INVISIBLE);
}
holder.txtTitle.setText(product.getOverview());
holder.txtprovider.setText(product.getProvider());
holder.counterParty.setText(product.getCounterparty());
holder.closingDate.setText(dateKoKaro(product.getClosingDate().toString()));
holder.term.setText(product.getTerm());
holder.indexLink.setText(product.getIndexLink());
holder.investmentType.setText(product.getInvestmentType());
holder.productType.setText(product.getProductType());
return row;
}
public String dateKoKaro(String datu){
/*Pattern pat = Pattern.compile("\\d.?.?.?.?-.?.?.?.?.?");
Matcher mat = pat.matcher(datu);
String dx = new String();
while(mat.find()){
dx = mat.group();
}
System.out.println(dx);*/
String l = new SimpleDateFormat("yyyy-MM-dd").format(new Date(Long.parseLong(datu)));
System.out.println("THE TIME: "+l);
String[] dxxx = l.split("-");
Calendar c = Calendar.getInstance();
System.out.println("Y: "+Integer.parseInt(dxxx[0])+" - "+"M: "+Integer.parseInt(dxxx[1])+" - "+"D: "+Integer.parseInt(dxxx[2]));
if(Integer.parseInt(dxxx[1])==0){
c.set(Integer.parseInt(dxxx[0]), Integer.parseInt(dxxx[1]), Integer.parseInt(dxxx[2]));
}
else{
c.set(Integer.parseInt(dxxx[0]), Integer.parseInt(dxxx[1])-1, Integer.parseInt(dxxx[2]));
}
Date d = c.getTime();
DateFormat df = DateFormat.getDateInstance(DateFormat.LONG);
String InDate = df.format(d);
return InDate;
}
static class WeatherHolder
{
ImageView imgIcon;
ImageView imgIsPreffered;
TextView txtTitle;
TextView txtprovider;
TextView counterParty;
TextView closingDate;
TextView term;
TextView indexLink;
TextView investmentType;
TextView productType;
LinearLayout li;
}
private Drawable LoadImageFromWebOperations(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
System.out.println("Exc=" + e);
return null;
}
}
}
public class ProductActivity extends Activity{
public APIHandlingClass api = APIHandlingClass.getInstance();
public static ArrayList<ProductListPojo> apList = new ArrayList<ProductListPojo>();
public ListView lv;
int count = 0;
ProductListPojo pPojo;
ProductAdapter adpt;
View mheader;
View mfooter;
boolean isInternet = false;
Intent i;
Button mbuttFilter;
Button mback;
/*Button mbuttonLiterature;
Button mbuttonQuestion;*/
Handler h;
ProgressDialog pd;
DataBaseHelper dkarkeB = new DataBaseHelper(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.productlist);
/*mbuttonLiterature = (Button)findViewById(R.id.buttonLiterature);
mbuttonQuestion = (Button)findViewById(R.id.buttonQuestion);*/
mheader = View.inflate(ProductActivity.this, R.layout.headerproductlist, null);
mfooter = View.inflate(ProductActivity.this, R.layout.giraffeimg, null);
lv = (ListView)findViewById(R.id.listView_ProductList);
adpt = new ProductAdapter(ProductActivity.this, R.layout.productitem , apList);
lv.addHeaderView(mheader,null,false);
lv.addFooterView(mheader,null,false);
lv.addFooterView(mfooter,null,false);
mback = (Button)findViewById(R.id.button_Filter);
h = new Handler();
pd = new ProgressDialog(getParent());
pd.setTitle("Loading...");
apList.clear();
if(InternetAvailable()){
System.out.println("Net hai");
pd.show();
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute();
}else{
System.out.println("Net nahi hai");
DownloadWebPageNewTask t = new DownloadWebPageNewTask();
t.execute();
//adpt = new ProductAdapter(ProductActivity.this, R.layout.productitem , apList);
//fillList();
/*adpt = new ProductAdapter(ProductActivity.this, R.layout.productitem , apList);
lv.setAdapter(adpt);
adpt.notifyDataSetChanged();*/
AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(getParent());
myAlertDialog.setTitle("--- Network Erro ---");
myAlertDialog.setMessage("We were unable to connect to the Internet to download product information. Please ensure you have an active data connection and restart the app.");
myAlertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
arg0.dismiss();
}});
System.out.println("No Internet Connectivity");
myAlertDialog.show();
}
mbuttFilter = (Button)findViewById(R.id.button_Filter);
/*mbuttFilter.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
i = new Intent(ProductActivity.this, ResetActivity.class);
startActivity(i);
}
});*/
mback.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
i = new Intent(ProductActivity.this, ResetActivity.class);
startActivity(i);
}
});
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
i = new Intent(ProductActivity.this,ProductDetails.class);
//i.putExtra("keyAapo", arg2 );
i.putExtra("keyAapo", (int)lv.getItemIdAtPosition(arg2) );
startActivity(i);
}
});
/*mbuttonLiterature.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
i = new Intent(ProductActivity.this, GetLiteratureActivity.class);
startActivity(i);
}
});
mbuttonQuestion.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
i = new Intent(ProductActivity.this, AnyQuestionActivity.class);
startActivity(i);
}
});
*/
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String response = "";
parseJson();
fillList();
return response;
}
@Override
protected void onPostExecute(String result) {
h.postDelayed(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
pd.dismiss();
}
}, 3000);
adpt = new ProductAdapter(ProductActivity.this, R.layout.productitem , apList);
/*lv.addHeaderView(mheader,null,false);
lv.addFooterView(mheader,null,false);
lv.addFooterView(mfooter,null,false);*/
lv.setAdapter(adpt);
adpt.notifyDataSetChanged();
}
}
/////--------------------------------------------------------------------------------------------------
private class DownloadWebPageNewTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String response = "";
fillList();
return response;
}
@Override
protected void onPostExecute(String result) {
h.postDelayed(new Runnable() {
@Override
public void run() {
pd.dismiss();
}
}, 3000);
adpt = new ProductAdapter(ProductActivity.this, R.layout.productitem , apList);
lv.setAdapter(adpt);
adpt.notifyDataSetChanged();
}
}
/////--------------------------------------------------------------------------------------------------
public void parseJson(){
JSONArray jarr;
dkarkeB.openDataBase();
dkarkeB.deleteAll();
dkarkeB.close();
try {
jarr = api.go();
for(int i=0 ; i<jarr.length() ; i++){
JSONObject jobj = jarr.getJSONObject(i);
String mainText = new String();
String provText = new String();
String couText = new String();
String fDatu = new String();
String termText = new String();
String indexText = new String();
String insvText = new String();
String prodText = new String();
String isPref = new String();
String jDesc = new String();
String jCb1 = new String();
String jCb2 = new String();
String jCb3 = new String();
String jCb4 = new String();
String jspRating = new String();
String jFRating = new String();
String jMRating = new String();
String jFs = new String();
String jColl = new String();
String jSIndex = new String();
String jEIndex = new String();
String jCashISA = new String();
String jEquityISA = new String();
String jDirect = new String();
String jTransfer = new String();
String jSipp = new String();
String jCapitalAtRiskProDetails = new String();
String jCapitalAtRiskProPercentage = new String();
String jProValue = new String();
String jInitialsCharges = new String();
String jEarlyISATransfer = new String();
String pid= new String();
String jOpinionExplanation = new String();
String jName = new String();
String jTaxTreat = new String();
String jDownSide = new String();
String jProtectionDetails = new String();
String jEarlySurrender = new String();
String jOtherCharges = new String();
try{
mainText = jobj.getString("Overview");
System.out.println(mainText);
}catch(Exception ex){
}
try{
JSONObject jProv = jobj.getJSONObject("Provider");
provText = jProv.getString("Name");
System.out.println(provText);
}catch(Exception ex){
}
try{
JSONObject jCou = jobj.getJSONObject("Counterparty");
couText = jCou.getString("Value");
System.out.println(couText);
}catch(Exception ex){
}
try{
String cloText = jobj.getString("ClosingDate");
fDatu = giveMeDate(cloText);
System.out.println(fDatu);
}catch(Exception ex){
}
try{
termText = jobj.getString("Term");
System.out.println(termText);
}catch(Exception ex){
}
try{
indexText = jobj.getString("IndexLink");
System.out.println(indexText);
}catch(Exception ex){
}
try{
JSONObject jInsv = jobj.getJSONObject("InvestmentType");
insvText = jInsv.getString("Value");
System.out.println(insvText);
}catch(Exception ex){
}
try{
JSONObject jProd = jobj.getJSONObject("ProductType");
prodText = jProd.getString("Value");
System.out.println(prodText);
}catch(Exception ex){
}
try{
isPref = BooleanToString(jobj.getBoolean("IsPreferred"));
System.out.println(isPref);
}catch(Exception ex){
}
try{
jDesc = jobj.getString("Description");
System.out.println(jDesc);
}catch(Exception ex){
}
try{
jCb1 = jobj.getString("CashBackTier1");
System.out.println(jCb1);
}catch(Exception ex){
}
try{
jCb2 = jobj.getString("CashBackTier2");
System.out.println(jCb2);
}catch(Exception ex){
}
try{
jCb3 = jobj.getString("CashBackTier3");
System.out.println(jCb3);
}catch(Exception ex){
}
try{
jCb4 = jobj.getString("CashBackTier4");
System.out.println(jCb4);
}catch(Exception ex){
}
try{
JSONObject jSP = jobj.getJSONObject("SPRating");
jspRating = jSP.getString("Rating");
System.out.println(jspRating);
}catch(Exception ex){
}
try{
JSONObject jFr = jobj.getJSONObject("FitchRating");
jFRating = jFr.getString("Rating");
System.out.println("I am the Fitch:"+jFRating);
}catch(Exception ex){
}
try{
JSONObject jMdy = jobj.getJSONObject("MoodyRating");
jMRating = jMdy.getString("Rating");
System.out.println(jMRating);
}catch(Exception ex){
}
try{
jFs = BooleanToString(jobj.getBoolean("IsFSCSProtected"));
System.out.println(jFs);
}catch(Exception ex){
}
try{
jColl = BooleanToString(jobj.getBoolean("IsCollateralised"));
System.out.println(jColl);
}catch(Exception ex){
}
try{
jSIndex = jobj.getString("StartingIndices");
System.out.println(jSIndex);
}catch(Exception ex){
}
try{
jEIndex = jobj.getString("FinalIndices");
System.out.println(jEIndex);
}catch(Exception ex){
}
try{
jCashISA = jobj.getString("MinimumCashISA");
System.out.println(jCashISA);
}catch(Exception ex){
}
try{
jEquityISA = jobj.getString("MinimumEquityISA");
System.out.println(jEquityISA);
}catch(Exception ex){
}
try{
jDirect = jobj.getString("MinimumDirect");
System.out.println(jDirect);
}catch(Exception ex){
}
try{
jTransfer = jobj.getString("MinimumTransfer");
System.out.println(jTransfer);
}catch(Exception ex){
}
try{
jSipp = jobj.getString("MinimumSIPP");
System.out.println(jSipp);
}catch(Exception ex){
}
try{
jCapitalAtRiskProDetails = jobj.getString("ProtectionDetails");
System.out.println(jCapitalAtRiskProDetails);
}catch(Exception ex){
}
try{
jCapitalAtRiskProPercentage = jobj.getString("ProtectionPercentage");
System.out.println(jCapitalAtRiskProPercentage);
}catch(Exception ex){
}
try{
JSONObject jVal = jobj.getJSONObject("ProtectionType");
jProValue = jVal.getString("Value");
System.out.println(jProValue);
}catch(Exception ex){
}
try{
jInitialsCharges = jobj.getString("InitialCharge");
System.out.println(jInitialsCharges);
}catch(Exception ex){
}
try{
jEarlyISATransfer = jobj.getString("EarlyISATransferCharge");
System.out.println(jEarlyISATransfer);
}catch(Exception ex){
}
try{
jOpinionExplanation = jobj.getString("OpinionExplanation");
System.out.println("xxxxXXXX"+jOpinionExplanation);
}catch(Exception ex){
}
try{
pid = jobj.getString("ID");
}catch(Exception ex){
}
try{
jName = jobj.getString("Name");
System.out.println(jName);
}catch(Exception ex){
}
try{
jTaxTreat = jobj.getString("TaxTreatment");
System.out.println(jTaxTreat);
}catch(Exception ex){
}
try{
jDownSide = jobj.getString("Downside");
System.out.println(jDownSide);
}catch(Exception ex){
}
try{
jProtectionDetails = jobj.getString("ProtectionDetails");
System.out.println(jProtectionDetails);
}catch(Exception ex){
}
try{
jEarlySurrender = jobj.getString("SurrenderCharge");
System.out.println(jEarlySurrender);
}catch(Exception ex){
}
try{
jOtherCharges = jobj.getString("OtherCharge");
System.out.println(jOtherCharges);
}catch(Exception ex){
}
dkarkeB.openDataBase();
dkarkeB.insertTitle( mainText, jDesc,
jCb1, jCb2, jCb3,
jCb4, jspRating, jFRating,
jMRating, jFs , jColl,
jSIndex, jEIndex, jCashISA,
jEquityISA, jDirect, jTransfer,
jSipp,jCapitalAtRiskProDetails,
jCapitalAtRiskProPercentage, jProValue,
jInitialsCharges, jEarlyISATransfer,
provText, couText, fDatu,
termText, indexText, insvText,
prodText, isPref, pid, jOpinionExplanation,jName, jTaxTreat, jDownSide, jProtectionDetails, jEarlySurrender, jOtherCharges);
dkarkeB.close();
}
System.out.println("SIZE DOES MATTER IN LIST: "+jarr.length());
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
public void fillList(){
dkarkeB.openDataBase();
apList = dkarkeB.getMyProductList();
dkarkeB.close();
}
public String BooleanToString(boolean isKaro){
String holdIt = new String();
if(isKaro){
holdIt = "true";
}
else{
holdIt = "false";
}
return holdIt;
}
public String giveMeDate(String str){
String s = str;
Pattern pat = Pattern.compile("\\d.?.?.?.?-.?.?.?.?.?");
Matcher mat = pat.matcher(s);
String datu = new String();
while(mat.find()){
datu = mat.group();
}
String dtx = new String();
////-----------------------------------------
try {
//String str_date="2012-09-12";
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("yyyy-MM-dd");
date = (Date)formatter.parse(datu);
long longDate=date.getTime();
System.out.println("Today is " +longDate );
System.out.println("New "+new SimpleDateFormat("yyyy-MM-dd").format(new Date(longDate)));
dtx = longDate+"";
}
catch (ParseException e){
System.out.println("Exception :"+e);
}
////------------------------------------------
/*String[] dxxx = datu.split("-");
Calendar c = Calendar.getInstance();
c.set(Integer.parseInt(dxxx[0]), Integer.parseInt(dxxx[1]), Integer.parseInt(dxxx[2]));
Date d = c.getTime();
DateFormat df = DateFormat.getDateInstance(DateFormat.LONG);
String InDate = df.format(d);*/
return dtx;
}
//////----------------------------------------------------Internet-------------------------------------------
public boolean InternetAvailable() {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
// while(isStopMe){
System.out.println("This is inside ................. :");
try {
if (!checkConnection()) {
System.out.println("No Internet Connectivity");
ProductActivity.this.isInternet = false;
System.out.println("First");
} else {
if (inetAddr()) {
System.out.println("Net Connectivity is Present");
ProductActivity.this.isInternet = true;
System.out.println("Second");
} else {
if (mobileConnect()) {
System.out.println("THIRD");
if (inetAddr()) {
System.out
.println("Net Connectivity is Present");
ProductActivity.this.isInternet = true;
System.out.println("FOURTH");
} else {
System.out
.println("No Internet Connectivity");
ProductActivity.this.isInternet = false;
System.out.println("FIFTH");
}
} else {
System.out.println("No Internet Connectivity");
ProductActivity.this.isInternet = false;
System.out.println("SIX");
}
}
}
} catch (Exception ex) {
System.out.println("Leak ko catch");
}
}
});
t.start();
try {
t.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ProductActivity.this.isInternet;
}
public boolean checkConnection() {
boolean connected = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm != null) {
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if ((ni.getTypeName().equalsIgnoreCase("WIFI") || ni
.getTypeName().equalsIgnoreCase("MOBILE"))
& ni.isConnected() & ni.isAvailable()) {
connected = true;
}
}
}
return connected;
}
public boolean inetAddr() {
boolean x1 = false;
try {
Socket s = new Socket();
s.connect(new InetSocketAddress("ntp-nist.ldsbc.edu",37),3000);
InputStream is = s.getInputStream();
Scanner scan = new Scanner(is);
while(scan.hasNextLine()){
System.out.println(scan.nextLine());
x1 = true;
}
} catch (IOException e) {
x1 = false;
}
return x1;
}
public boolean mobileConnect() {
boolean conn = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNet = cm
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (activeNet != null) {
conn = true;
} else {
conn = false;
}
return conn;
}
/////-----------------------------------------------------Internet-------------------------------------------
@Override
protected void onResume() {
super.onResume();
//adpt.notifyDataSetChanged();
System.out.println("The List is: "+apList+"::"+apList.size());
if(count>0){
adpt = new ProductAdapter(ProductActivity.this, R.layout.productitem , apList);
lv.setAdapter(adpt);
}
count++;
System.out.println("The List is: "+apList+"::"+apList.size());
}
}
ArrayList<Tumblr> tumblrs = new ArrayList<Tumblr>();
public class Example extends Activity {
Context context = null;
ListView listView = null;
TextView footer;
int offset = 0;
ProgressDialog pDialog;
ArrayList<Tumblr> tumblrs;
private String searchUrl = "http://api.tumblr.com/v2/blog/factsandchicks.com/posts? api_key=API_KEY&offset=0";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
tumblrs = getTumblrs();
listView = (ListView) findViewById(R.id.list);
View v = getLayoutInflater().inflate(R.layout.footer_layout, null);
footer = (TextView) v.findViewById(R.id.tvFoot);
listView.addFooterView(v);
listView.setAdapter(new UserItemAdapter(this, R.layout.listitem));
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
footer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new loadMoreListView().execute();
}
});
public class UserItemAdapter extends ArrayAdapter<Tumblr> {
public UserItemAdapter(Context context, int imageViewResourceId) {
super(context, imageViewResourceId, tumblrs);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.listitem, null);
}
Tumblr tumblr = tumblrs.get(position);
if (tumblr != null) {
ImageView image = (ImageView) v.findViewById(R.id.avatar);
if (image != null) {
image.setImageBitmap(getBitmap(tumblr.image_url));
}
}
return v;
}
}
public Bitmap getBitmap(String bitmapUrl) {
try {
URL url = new URL(bitmapUrl);
return BitmapFactory.decodeStream(url.openConnection()
.getInputStream());
} catch (Exception ex) {
return null;
}
}
public ArrayList<Tumblr> getTumblrs() throws ClientProtocolException,
IOException, JSONException {
searchUrl = "http://api.tumblr.com/v2/blog/factsandchicks.com/posts?api_key=API_KEY&offset=0";
ArrayList<Tumblr> tumblrs = new ArrayList<Tumblr>();
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(searchUrl);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = null;
try {
responseBody = client.execute(get, responseHandler);
} catch (Exception ex) {
ex.printStackTrace();
}
JSONObject jsonObject = new JSONObject(responseBody);
JSONArray posts = jsonObject.getJSONObject("response").getJSONArray(
"posts");
for (int i = 0; i < posts.length(); i++) {
JSONArray photos = posts.getJSONObject(i).getJSONArray("photos");
for (int j = 0; j < photos.length(); j++) {
JSONObject photo = photos.getJSONObject(j);
String url = photo.getJSONArray("alt_sizes").getJSONObject(0)
.getString("url");
Tumblr tumblr = new Tumblr(url);
tumblrs.add(tumblr);
}
}
return tumblrs;
}
}
public class Tumblr {
public String image_url;
public Tumblr(String url) {
this.image_url = url;
}
}
private class loadMoreListView extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
// Showing progress dialog before sending http request
pDialog = new ProgressDialog(Example.this);
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... unused) {
// TODO Auto-generated method stub
runOnUiThread(new Runnable() {
public void run() {
// increment current page
offset += 20;
// Next page request
searchUrl = "http://api.tumblr.com/v2/blog/factsandchicks.com/posts? api_key=API_KEY&limit=2&offset="
+ offset;
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(searchUrl);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = null;
try {
responseBody = client.execute(get, responseHandler);
} catch (Exception ex) {
ex.printStackTrace();
}
JSONObject jsonObject;
try {
jsonObject = new JSONObject(responseBody);
JSONArray posts = jsonObject.getJSONObject("response")
.getJSONArray("posts");
for (int i = 0; i < posts.length(); i++) {
JSONArray photos = posts.getJSONObject(i)
.getJSONArray("photos");
for (int j = 0; j < photos.length(); j++) {
JSONObject photo = photos.getJSONObject(j);
String url = photo.getJSONArray("alt_sizes")
.getJSONObject(0).getString("url");
Tumblr tumblr = new Tumblr(url);
tumblrs.add(tumblr);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// get listview current position - used to maintain scroll
// position
int currentPosition = listView.getFirstVisiblePosition();
// Appending new data to tumblrs ArrayList
// Setting new scroll position
listView.setSelectionFromTop(currentPosition + 1, 0);
}
});
return null;
}
protected void onPostExecute(Void unused) {
pDialog.dismiss();
}
}