First time SharedPreferences use with GridView - android

This is my Apps Screenshoot :
There is two button in that GridView : +/-.
So what im gonna try is when i press "+" button or "-" button, the quantity is store in SharedPreferences.
But really im confused about this.
This is my code so far :
package com.android.customer_blanjapasar.Utility;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.customer_blanjapasar.R;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Leon on 5/3/2016.
*/
public class CustomGridView2 extends BaseAdapter {
private ArrayList<ListItem> listData;
private LayoutInflater layoutInflater;
private Context context;
private String[] imageUrls;
private int count = 0;
int arrayCount[];
SharedPreferences prefs ;
SharedPreference sharedPreference;
public CustomGridView2(Context context, ArrayList<ListItem> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
this.context = context;
sharedPreference = new SharedPreference();
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.afterlogin_product_gridview, null);
holder = new ViewHolder();
holder.headlineView = (TextView) convertView.findViewById(R.id.nama_produk);
holder.teaserView = (TextView) convertView.findViewById(R.id.harga);
holder.imageView = (ImageView) convertView.findViewById(R.id.img_produk);
holder.cmdMinus = (Button) convertView.findViewById(R.id.btn_min);
holder.cmdPlus = (Button) convertView.findViewById(R.id.btn_plus);
holder.qty = (TextView) convertView.findViewById(R.id.lbl_qty);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ListItem newsItem = listData.get(position);
String satuan = newsItem.getSatuan().toString();
String harga = newsItem.getReporterName().toString();
harga = "Rp. " + harga + " / " + satuan;
holder.headlineView.setText(newsItem.getHeadline().toUpperCase());
holder.teaserView.setText(harga);
String a = newsItem.getUrl();
holder.cmdPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count = Integer.parseInt( holder.qty.getText().toString());
count++;
holder.qty.setText(""+count);
}
});
holder.cmdMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count = Integer.parseInt( holder.qty.getText().toString());
if(count == 0) {
holder.qty.setText("0");
}
else {
count--;
holder.qty.setText("" + count);
}
}
});
if (holder.imageView != null) {
//new ImageDownloaderTask(holder.imageView).execute(newsItem.getUrl());
Picasso
.with(context)
.load(a)
.fit()
.into(holder.imageView);
}
return convertView;
}
static class ViewHolder {
TextView headlineView;
TextView teaserView;
ImageView imageView;
TextView satuan,qty;
Button cmdPlus,cmdMinus;
}
}
I already see this tutorial. But im still getting confused. Please guide me step by step.
EDIT
This is ListItem.class :
public class ListItem {
private String headline;
private String reporterName;
private String kode;
private String url;
private String satuan;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getHeadline() {
return headline;
}
public void setHeadline(String headline) {
this.headline = headline;
}
public String getReporterName() {
return reporterName;
}
public void setReporterName(String reporterName) {
this.reporterName = reporterName;
}
public String getKode() {
return kode;
}
public void setKode(String kode) {
this.kode = kode;
}
public String getSatuan() {
return satuan;
}
public void setSatuan(String satuan) {
this.satuan = satuan;
}
#Override
public String toString() {
return "[ headline=" + headline + ", reporter Name=" + reporterName + " , date=" + kode + "]";
}
}
And this is the code inside MainActivity.class :
public class AfterLogin_Produk extends Activity {
Activity activity;
ImageButton btn_resep,btn_product;
static int jArray;
GridView product_gridview;
static String[] nama_prdct;
static String[] img_prdct;
static String[] harga_prdct;
static String[] satuan_prdct;
static String kode_ktgr;
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.after_login_produk_main);
product_gridview = (GridView) findViewById(R.id.product_gridview);
new GetLength().execute();
}
public ArrayList<ListItem> getListData() {
ArrayList<ListItem> listMockData = new ArrayList<ListItem>();
for (int i = 0; i < jArray; i++) {
ListItem newsData = new ListItem();
newsData.setUrl(img_prdct[i]);
newsData.setHeadline(nama_prdct[i]);
newsData.setReporterName(harga_prdct[i]);
newsData.setSatuan(satuan_prdct[i]);
listMockData.add(newsData);
}
return listMockData;
}
class GetLength extends AsyncTask<String, String, String> {
String nama_product,img_product,harga_product,satuan_product;
JSONParser2 jParser = new JSONParser2();
ArrayList<String> list_nama_produk = new ArrayList<String>();
ArrayList<String> list_img_produk = new ArrayList<String>();
ArrayList<String> list_harga_produk = new ArrayList<String>();
ArrayList<String> list_satuan_produk = new ArrayList<String>();
protected String doInBackground(String... params) {
try {
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("kode_kategori", kode_ktgr));
JSONObject json = jParser.makeHttpRequest("http:xxx.php", "POST", param);
JSONArray array = json.getJSONArray("categories");
jArray = array.length();
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
nama_product = row.getString("nama_produk");
img_product = row.getString("img_produk");
harga_product = row.getString("harga_satuan");
satuan_product = row.getString("nama_satuan");
list_nama_produk.add(nama_product);
list_img_produk.add(img_product);
list_harga_produk.add(harga_product);
list_satuan_produk.add(satuan_product);
}
} catch (Exception e) {
System.out.println("Exception : " + e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//Toast.makeText(getBaseContext(),"Value : " + list_nama_kategori,Toast.LENGTH_SHORT).show();
nama_prdct = new String[list_nama_produk.size()];
img_prdct = new String[list_img_produk.size()];
harga_prdct = new String[list_harga_produk.size()];
satuan_prdct = new String[list_satuan_produk.size()];
nama_prdct = list_nama_produk.toArray(nama_prdct);
img_prdct = list_img_produk.toArray(img_prdct);
harga_prdct = list_harga_produk.toArray(harga_prdct);
satuan_prdct = list_satuan_produk.toArray(satuan_prdct);
ArrayList<ListItem> listData = getListData();
product_gridview.setAdapter(new CustomGridView2(AfterLogin_Produk.this, listData));
}
}

you are using custom array list of object than set propertie to it and on back press of application you can jsonify your object to string and store it in shared preference and at activity on create you can regenerate your object getting from shared preference. in activity onCreate()
SharedPreferences mSettings = PreferenceManager.getDefaultSharedPreferences
(Dashboard.this);
String data = mSettings.getString("data", "");
/* Should Activity Check for Updates Now? */
if ((data.equals(""))) {
//do nothing data is not in shared preference
}
else {
//data is there convert To object
data=mSettings.getString("data", "");
Type listType = new TypeToken<ArrayList<ListRowItem>>() {
}.getType();
ArrayList<ListRowItem> listRowItems = new Gson().fromJson(data, listType);
//setAdapter coming for arrayList as usual.
}
and in backPressed you can read data from adapter and jsonify it using json and put it in sharedPreference
i hope you understand the login . clear preference after data set.

Your issue is here:
holder.qty.setText(store);
It is clearly pointed out in your error log:
android.content.res.Resources$NotFoundException: String resource ID
0x1 at android.content.res.Resources.getText(Resources.java:1409) at android.widget.TextView.setText(TextView.java:4943)
store is an integer and setText is trying to look for a resource with this id. Use this instead.
holder.qty.setText(store.toString());
Also, to reduce the complexity of shared preferences specific code you can use this library

Related

How to send multiple selected check box values to a server?

I want to send multiple selected checkbox travel id value to a server.
The code is working, but the value is not updating.
When the submit button is pressed, I want all the selected checkbox values to be sent to the server and the selected check box values are updated on the server.
package com.example.fiffa.fifaa;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ViewSubmission extends AppCompatActivity{
final Context context = this;
ListView listView;
String travelid;
TextView txtvisit,txtsum,txtsystem;
Button submit,back;
String MyPREFERENCES = "loginInfo";
SharedPreferences sharedpreferences;
ProgressDialog pDialog;
String ss="";
String userid;
boolean[] present;
boolean[] absent;
String takenatt="";
double gtotal=0.0;
List<Submitconvencelistitem> rowItems;
ArrayList<Submitconvencelistitem> feedsList;
Submitconvenceadapter adapter;
int count;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_submission);
submit = (Button) findViewById(R.id.submit);
back = (Button) findViewById(R.id.backviewsub);
txtvisit=(TextView)findViewById(R.id.txtvisit);
txtsum=(TextView)findViewById(R.id.txttotal);
//txtsystem=(TextView)findViewById(R.id.txtsystem);
listView = (ListView) findViewById(R.id.lstconveynce);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent viewsub=new Intent(ViewSubmission.this,Submitconveyance.class);
startActivity(viewsub);
}
});
String viewdata = getIntent().getExtras().getString("response", "");
Log.e("viewdata", viewdata);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
//conveyncetravelid = sharedpreferences.getString("travelid", "");
//Log.e("econveyncetravelid", conveyncetravelid);
userid = sharedpreferences.getString("userId", "");
Log.e("userId", userid);
try {
//feedsList=getSubmit(false);
JSONArray js = new JSONArray(viewdata);
feedsList=new ArrayList<>();
for (int i = 0; i < js.length(); i++) {
JSONObject jObject = js.getJSONObject(i);
Submitconvencelistitem st=new Submitconvencelistitem();
String total_amount=jObject.getString("total_amount");
Log.e("total_amount",total_amount);
//String travelid = jObject.getString("travelid");
//Log.e("conveyncetravelid", travelid);
st.settravelid(jObject.optString("travelid"));
st.setsubdate(jObject.optString("startdate"));
st.setstartlocation(jObject.optString("startlocation"));
st.setendlocation(jObject.optString("endlocation"));
st.setccno(jObject.optString("cc_no"));
st.setcustomername(jObject.optString("custname"));
st.setcallstatus(jObject.optString("callstatus"));;
st.setmodeofconveynce(jObject.optString("travel_mode"));
st.setkmstravelled(jObject.optString("KM"));
st.setclaimamout(jObject.optString("total_amount"));
//st.setSelected(true);
feedsList.add(st);
/* gtotal += Double.parseDouble(feedsList.get(i).getclaimamout());
Log.e("Total", String.valueOf(gtotal));
txtsum.setText(Double.toString(gtotal));*/
//Toast.makeText(MainActivity.this,result.toString(),Toast.LENGTH_LONG).show();
/* Log.e("shams", viewdata.toString());
String startdate = js.getJSONObject(0).getString("startdate");
Log.e("startdate",startdate);
String startlocation = js.getJSONObject(0).getString("startlocation");
Log.e("startlocation",startlocation);
String endlocation = js.getJSONObject(0).getString("endlocation");
Log.e("endlocation",endlocation);
String cc_no = js.getJSONObject(0).getString("cc_no");
Log.e("cc_no",cc_no);
String custname = js.getJSONObject(0).getString("custname");
Log.e("custname",custname);
String callstatus = js.getJSONObject(0).getString("callstatus");
Log.e("callstatus",callstatus);
String travel_mode = js.getJSONObject(0).getString("travel_mode");
Log.e("travel_mode",travel_mode);
String KM = js.getJSONObject(0).getString("KM");
Log.e("KM",KM);
String total_amount = js.getJSONObject(0).getString("total_amount");
Log.e("total_amount",total_amount);
st.setsubdate(startdate);
st.setstartlocation(startlocation);
st.setendlocation(endlocation);
st.setccno(cc_no);
st.setcustomername(custname);
st.setcallstatus(callstatus);
st.setmodeofconveynce(travel_mode);
st.setkmstravelled(KM);
st.setclaimamout(total_amount);
st.setSelected(true);*//*
feedsList.add(st);*/
/* JSONObject post = js.getJSONObject(i);
Submitconvencelistitem st=new Submitconvencelistitem();
st.setsubdate(post.optString("startdate"));
st.setstartlocation(post.optString("startlocation"));
st.setendlocation(post.optString("endlocation"));
st.setccno(post.optString("cc_no"));
st.setcustomername(post.optString("custname"));
st.setcallstatus(post.optString("callstatus"));
st.setmodeofconveynce(post.optString("travel_mode"));
st.setkmstravelled(post.optString("KM"));
st.setclaimamout(post.optString(("total_amount")));
st.setSelected(true);
feedsList.add(st);*/
}
adapter = new Submitconvenceadapter(ViewSubmission.this, feedsList);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
count=adapter.getCount();
txtvisit.setText(Integer.toString(count));
}
catch (JSONException e) {
e.printStackTrace();
}
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//final List<Submitconvencelistitem> selectedItems = adapter.getSelectedItems();
//Use this data for sending to your webserver
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ViewSubmission.this);
alertDialogBuilder.setMessage("Submit the Selected Conveynce");
alertDialogBuilder.setPositiveButton("yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
for (int strt=0;strt<present.length;strt++) {
if (present[strt]) {
travelid = feedsList.get(strt).gettravelid();
}
new Asyncupdate_travelforconv().execute();
}
//Toast.makeText(ViewSubmission.this,"Your conveyance has been submitted ",Toast.LENGTH_LONG).show();
}
});
alertDialogBuilder.setNegativeButton("No",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent view=new Intent(ViewSubmission.this,Submitconveyance.class);
startActivity(view);
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
//new Asncselect_travelforconvsub().execute();
}
});
}
/* private ArrayList<Submitconvencelistitem> getSubmit(boolean isSelect){
ArrayList<Submitconvencelistitem> list = new ArrayList<>();
for(int i = 0; i < feedsList.size(); i++){
Submitconvencelistitem st = new Submitconvencelistitem();
st.setSelected(isSelect);
feedsList.add(st);
}
return list;
}
*/
/*Asynctask For Insertstart travel details*/
private class Asyncupdate_travelforconv extends AsyncTask<String, Integer, String> {
String SOAP_ACTION = "http://tempuri.org/IFIFA/update_travelforconv";
String NAMESPACE = "http://tempuri.org/";
String METHOD_NAME = "update_travelforconv";
String URL = "http://migadget.aforeserve.co.in/FIFA.svc?singleWsdl";
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... strings) {
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("travelid", travelid);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
//envelope.setOutputSoapObject(request);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
Object result = null;
result = (Object) envelope.getResponse();
Log.e("conveynce", String.valueOf(result));
System.out.println("APIresult:" + result.toString());
ss = result.toString();
Log.e("APIRESULT", ss);
} catch (Exception e) {
System.out.println("Error" + e);
}
return ss;
} catch (Exception ex) {
ex.printStackTrace();
return "";
}
}
#Override
protected void onPostExecute(String result) {
Log.e("APIResult", result);
Toast.makeText(getBaseContext(), "Data Updated", Toast.LENGTH_LONG).show();
}
}
/*Adapter class For Submit conveynce */
public class Submitconvenceadapter extends BaseAdapter {
ArrayList<Submitconvencelistitem> listData;
private LayoutInflater layoutInflater;
Context context;
List<Submitconvencelistitem> rowItems;
String MyPREFERENCES = "loginInfo";
String travelid;
SharedPreferences sharedpreferences;
public Submitconvenceadapter(Context ViewSubmission,ArrayList<Submitconvencelistitem> results)
{
listData = results;
context=ViewSubmission;
present=new boolean[listData.size()];
Arrays.fill(present, true);
}
#Override
public int getCount()
{
return listData.size();
}
#Override
public Object getItem(int position)
{
return listData.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
final ViewHolder holder;
LayoutInflater layoutInflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_item_submitconveynce, null);
holder = new ViewHolder();
//holder.checkbox=(CheckBox) convertView.findViewById(R.id.cb1);
holder.date = (TextView) convertView.findViewById(R.id.subdate);
holder.startlocation = (TextView) convertView.findViewById(R.id.startlocation);
holder.endlocation=(TextView)convertView.findViewById(R.id.endlocation);
holder.ccno = (TextView) convertView.findViewById(R.id.ccno);
holder.customername = (TextView) convertView.findViewById(R.id.tv_name);
holder.callstatus = (TextView)convertView.findViewById(R.id.tv_callstatus);
holder.modeofconveynce = (TextView)convertView.findViewById(R.id.tv_modconveynce);
holder.Kmtravelled = (TextView)convertView.findViewById(R.id.tv_km);
holder.claimamount = (TextView)convertView.findViewById(R.id.claim_amount);
holder.checkbox=(CheckBox)convertView.findViewById(R.id.chk1);
/*//holder.checkbox.setChecked(true);
holder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
listData.get(position).setSelected(isChecked);
}
});*/
convertView.setTag(holder);
holder.checkbox.setChecked(present[position]);
}
else
{
holder = (ViewHolder) convertView.getTag();
holder.checkbox.setChecked(present[position]);
}
holder.checkbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (holder.checkbox.isChecked())
present[position] = true;
else
present[position] = false;
}
});
//travelid=listData.get(position).gettravelid();
//holder.travelid.setText(listData.get(position).gettravelid());
holder.date.setText(listData.get(position).getsubdate());
holder.startlocation.setText(listData.get(position).getstartlocation());
holder.endlocation.setText(listData.get(position).getendlocation());
holder.ccno.setText(listData.get(position).getccno());
holder.customername.setText(listData.get(position).getcustomername());
holder.callstatus.setText(listData.get(position).getcallstatus());
holder.modeofconveynce.setText(listData.get(position).getmodeofconveynce());
holder.Kmtravelled.setText(listData.get(position).getkmstravelled());
holder.claimamount.setText(listData.get(position).getclaimamout());
//holder.checkbox.setChecked(true);
return convertView;
}
public class ViewHolder {
CheckBox checkbox;
TextView date;
TextView startlocation;
TextView endlocation;
TextView ccno;
TextView customername;
TextView callstatus;
TextView modeofconveynce;
TextView Kmtravelled;
TextView claimamount;
TextView travelid;
}
/* public List<Submitconvencelistitem> getSelectedItems()
{
List<Submitconvencelistitem> selectedItems = new ArrayList<>();
for(Submitconvencelistitem item : listData)
{
selectedItems.add(item);
}
return selectedItems;
}*/
}
}
I am assuming that you are using php over your server.What you can do is send the comma separated travel id's over server like this:-
Put travel id's into an arraylist or array like this:-
ArrayList<String> selectedTravelId= new ArrayList<>();
selectedTravelId.add(travelId); // add travel ids
StringBuilder travelId = new StringBuilder();
for (int i = 0; i < selectedTravelId.size(); i++) {
travelId .append(selectedTravelId.get(i));
if (!(i == selectedTravelId.size() - 1)) {
travelId .append(",");
}
}// to create travelId string
travelId.toString();// to convert StringBuilder to String
After this execute your AsyncTask.
You will get a string like e.g. 1,2,134,142.Now send this travelId to sever.
At server side retrieve
Try explode:
$mytravelId = " 1,2,134,142";
$myArray = explode(',', $mytravelId );
print_r($myArray);
Output :
Array
(
[0] => 1
[1] => 2
[2] => 134
[3] => 142
)

on Click of text View inside a List Item not getting proper value

I have a ListView ,In that each ListItem having some items(textViews),In which one textView is having click event.That I have put in my custom adater,And I am calling an asynctask on its cLick event,For that I want a value when I click on that textView its "queID" I want,But currently I am gettong it null..Please see my code and help me please..!
"qoute" is that textView.On which I have put click event.how to set"buyer_req_Id" and get tag on it?I currrently successfully get the tag on each "ListItem" Click event ,I want to set the same tag on ListItem's textView.Inside java class I have put only adapter,In which I want "buyer_request_id".
Adapter.java
package com.epe.yehki.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.epe.yehki.ui.BuyingreqActivity;
import com.epe.yehki.ui.BuyingreqActivity.GetQuoteList;
import com.epe.yehki.util.Const;
import com.example.yehki.R;
public class BuyingRequestAdapter extends BaseAdapter {
public ArrayList<HashMap<String, String>> BuyingRequestArray;
private Context mContext;
public BuyingRequestAdapter(Context paramContext, ArrayList<HashMap<String, String>> productList) {
this.mContext = paramContext;
this.BuyingRequestArray = productList;
}
public int getCount() {
return this.BuyingRequestArray.size();
}
public Object getItem(int paramInt) {
return BuyingRequestArray.get(paramInt);
}
public long getItemId(int paramInt) {
return paramInt;
}
#SuppressWarnings("static-access")
public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) {
LayoutInflater localLayoutInflater = (LayoutInflater) this.mContext.getSystemService("layout_inflater");
Viewholder localViewholder;
if (paramView == null) {
paramView = localLayoutInflater.inflate(R.layout.raw_buying_req, paramViewGroup, false);
localViewholder = new Viewholder();
localViewholder.sub = ((TextView) paramView.findViewById(R.id.sub));
localViewholder.expDate = ((TextView) paramView.findViewById(R.id.exp_date));
localViewholder.quote = ((TextView) paramView.findViewById(R.id.quote));
localViewholder.status = ((TextView) paramView.findViewById(R.id.status));
localViewholder.lastUpdate = ((TextView) paramView.findViewById(R.id.last_updated));
paramView.setTag(localViewholder);
} else {
localViewholder = (Viewholder) paramView.getTag();
}
System.out.println(":::::::::::::::values:::::::::::::::" + BuyingRequestArray.get(paramInt).get(Const.TAG_PRODUCT_NAME));
localViewholder.sub.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_PRODUCT_NAME));
localViewholder.expDate.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_EXPIRY_DATE));
localViewholder.lastUpdate.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_DATE_MODIFIED));
localViewholder.quote.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_QUOTE_COUNT));
localViewholder.quote.setTextColor(Color.parseColor("#0000ff"));
localViewholder.status.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_BUYING_REQUEST_STATUS));
localViewholder.quote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("::::::::::::::::::quote clicked...!!");
GetQuoteList getQuoteList = ((BuyingreqActivity) mContext).new GetQuoteList();
getQuoteList.execute();
}
});
return paramView;
}
static class Viewholder {
TextView sub;
TextView lastUpdate;
TextView expDate;
TextView quote;
TextView status;
}
}
java class(asynctask)
public class GetQuoteList extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(BuyingreqActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
scr_post.setVisibility(View.GONE);
scr_view.setVisibility(View.GONE);
quote_view.setVisibility(View.VISIBLE);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// String query = "?customer_id=" +
// Pref.getValue(BuyingreqActivity.this, Const.PREF_CUSTOMER_ID, "")
// + "&buyer_request_id=23";
String query = "?customer_id=" + Pref.getValue(BuyingreqActivity.this, Const.PREF_CUSTOMER_ID, "") + "&buyer_request_id=" + buyer_request_id;
query = query.replace(" ", "%20");
viewURL = Const.API_QUOTE_RECIEVED + query;
BackendAPIService sh = new BackendAPIService();
System.out.println(":::::::::::::::::::ADDRESS URL:::::::::::::::::" + viewURL);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(viewURL, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
if (jsonObj.has(Const.TAG_BUYING_REQUEST)) {
System.out.println("::::::::::::::::true::::::::::::::::" + jsonObj.has(Const.TAG_ADDRESS_LIST));
requestes = jsonObj.getJSONArray(Const.TAG_BUYING_REQUEST);
if (requestes != null && requestes.length() != 0) {
// looping through All Contacts
System.out.println(":::::::::::FLAG IN SUB:::::::::::" + flag);
for (int i = 0; i < requestes.length(); i++) {
JSONObject c = requestes.getJSONObject(i);
buyerID = c.getString(Const.TAG_BUYING_REQUEST_ID);
System.out.println(":::::::::::::::MY buying request:::::::::::::" + buyerID);
String product_name = c.getString(Const.TAG_PRODUCT_NAME);
String quote_id = c.getString(Const.TAG_QUOTE_ID);
String supplier_name = c.getString(Const.TAG_SUPPLIER_NAME);
String status = c.getString(Const.TAG_STATUS);
HashMap<String, String> quote = new HashMap<String, String>();
quote.put(Const.TAG_BUYING_REQUEST_ID, buyerID);
quote.put(Const.TAG_PRODUCT_NAME, product_name);
quote.put(Const.TAG_QUOTE_ID, quote_id);
quote.put(Const.TAG_EXPIRY_DATE, supplier_name);
quote.put(Const.TAG_QUOTE_COUNT, status);
queList.add(quote);
System.out.println(":::::::::::::Buyer request ID:" + buyerID);
}
}
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("::::::::::::::::::got an error::::::::::::");
}
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
*
* */
quoteAdapter = new QuoteAdapter(BuyingreqActivity.this, queList);
quoteList.setAdapter(quoteAdapter);
}
}
// Try this way,hope this will help you...
localViewholder.quote.setTag(BuyingRequestArray.get(paramInt).get(Const.TAG_BUYING_REQUEST_ID));
localViewholder.quote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("::::::::::::::::::quote clicked...!!");
String buyerId = v.getTag().toString(); // user this buyerId for your requirement
System.out.println("Buyer Id Is "+buyerId);
GetQuoteList getQuoteList = ((BuyingreqActivity) mContext).new GetQuoteList();
getQuoteList.execute();
}
});
I have solved my problem as below by changing my asynctask to void to string :
adapter.java
package com.epe.yehki.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.epe.yehki.ui.BuyingreqActivity;
import com.epe.yehki.ui.BuyingreqActivity.GetQuoteList;
import com.epe.yehki.util.Const;
import com.example.yehki.R;
public class BuyingRequestAdapter extends BaseAdapter {
public ArrayList<HashMap<String, String>> BuyingRequestArray;
private Context mContext;
public BuyingRequestAdapter(Context paramContext, ArrayList<HashMap<String, String>> reqList) {
this.mContext = paramContext;
this.BuyingRequestArray = reqList;
}
public int getCount() {
return this.BuyingRequestArray.size();
}
public Object getItem(int paramInt) {
return BuyingRequestArray.get(paramInt);
}
public long getItemId(int paramInt) {
return paramInt;
}
#SuppressWarnings("static-access")
public View getView(final int paramInt, View paramView, ViewGroup paramViewGroup) {
LayoutInflater localLayoutInflater = (LayoutInflater) this.mContext.getSystemService("layout_inflater");
Viewholder localViewholder;
if (paramView == null) {
paramView = localLayoutInflater.inflate(R.layout.raw_buying_req, paramViewGroup, false);
localViewholder = new Viewholder();
localViewholder.sub = ((TextView) paramView.findViewById(R.id.sub));
localViewholder.expDate = ((TextView) paramView.findViewById(R.id.exp_date));
localViewholder.quote = ((TextView) paramView.findViewById(R.id.quote));
localViewholder.status = ((TextView) paramView.findViewById(R.id.status));
localViewholder.lastUpdate = ((TextView) paramView.findViewById(R.id.last_updated));
paramView.setTag(localViewholder);
/* localViewholder.quote.setTag(localViewholder); */
} else {
localViewholder = (Viewholder) paramView.getTag();
/* localViewholder.quote = ((TextView) paramView.getTag()); */
}
final String reqId = BuyingRequestArray.get(paramInt).get(Const.TAG_BUYING_REQUEST_ID);
System.out.println("::::::::::::::My reqId:::::::::::" + reqId);
localViewholder.sub.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_PRODUCT_NAME));
localViewholder.expDate.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_EXPIRY_DATE));
localViewholder.lastUpdate.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_DATE_MODIFIED));
localViewholder.quote.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_QUOTE_COUNT));
localViewholder.quote.setTextColor(Color.parseColor("#0000ff"));
localViewholder.status.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_BUYING_REQUEST_STATUS));
localViewholder.quote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("::::::::::::::::::quote clicked...!!");
System.out.println("Buyer Id Is " + reqId);
GetQuoteList getQuoteList = ((BuyingreqActivity) mContext).new GetQuoteList();
getQuoteList.execute(reqId);
}
});
return paramView;
}
static class Viewholder {
TextView sub;
TextView lastUpdate;
TextView expDate;
TextView quote;
TextView status;
}
}

Universal Image Loader using JSON instead of the Constants Class

I've got a functioning Universal Image Loader that I'm trying to switch to grabbing the image URLs from JSON rather than the Constants Class that it normally uses. I've created a JSON Parsing Class that outputs an ArrayList called galleryArrList. But I can't figure out how to implement my JSON Parsing class and also how to modify the Adapter class in the UILGrid class to accept the galleryArrList String. Here are the Classes:
UILGrid Class:
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.mysite.wcbc.UKVPConstants.Extra;
public class UILGrid extends AbsListViewBaseActivity {
String[] imageUrls;
DisplayImageOptions options;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.uil_grid);
Bundle bundle = getIntent().getExtras();
imageUrls = bundle.getStringArray(Extra.IMAGES);
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_stub)
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error).cacheInMemory(true)
.cacheOnDisc(true).bitmapConfig(Bitmap.Config.RGB_565).build();
listView = (GridView) findViewById(R.id.uil_gridview);
((GridView) listView).setAdapter(new ImageAdapter());
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
startImagePagerActivity(position);
}
});
}
private void startImagePagerActivity(int position) {
Intent intent = new Intent(this, CVP2.class); // ---- Change here
intent.putExtra(Extra.IMAGES, imageUrls);
intent.putExtra(Extra.IMAGE_POSITION, position);
startActivity(intent);
}
public class ImageAdapter extends BaseAdapter {
#Override
public int getCount() {
return imageUrls.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ImageView imageView;
if (convertView == null) {
imageView = (ImageView) getLayoutInflater().inflate(
R.layout.uil_grid_item, parent, false);
} else {
imageView = (ImageView) convertView;
}
imageLoader.displayImage(imageUrls[position], imageView, options);
return imageView;
}
}
}
my UILJSONParse Class:
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
public class UILJSONParse extends AsyncTask<String, String, JSONObject> {
// url to make request
private static String url = "http://www.mysite.com/apps/wcbc/galleryuil.txt";
// Hashmap for ListView
// ArrayList<HashMap<String, String>> arraylist;
ArrayList<HashMap<String, String>> galleryArrList = new ArrayList<HashMap<String, String>>();
// JSON Node names
private static final String TAG_GALLERY = "gallery";
private static final String TAG_GALLERYURL = "galleryurl";
private static final String TAG_ID = "id";
private static final String TAG_GALLERYDESCR = "gallerydescr";
// gallery JSONArray
JSONArray JSArrGallery = null;
#Override
protected JSONObject doInBackground(String... arg0) {
// Creating JSON Parser instance
JGrid4Adapter jParser = new JGrid4Adapter();
// getting JSON string from URL
JSONObject jsonOb = jParser.getJSONFromUrl(url);
return jsonOb;
}
#Override
protected void onPostExecute(JSONObject jsonOb) {
try {
JSArrGallery = jsonOb.getJSONArray(TAG_GALLERY);
// looping through All gallery images
for (int i = 0; i < JSArrGallery.length(); i++) {
JSONObject galleryJO = JSArrGallery.getJSONObject(i);
String idStr = galleryJO.getString(TAG_ID);
String urlStr = galleryJO.getString(TAG_GALLERYURL);
String descrStr = galleryJO.getString(TAG_GALLERYDESCR);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, idStr);
map.put(TAG_GALLERYURL, urlStr);
map.put(TAG_GALLERYDESCR, descrStr);
// adding HashMap map to ArrayList galleryArrList, defined
// above
galleryArrList.add(map);
}// -- END for loop
} catch (JSONException e) {
e.printStackTrace();
}// --- END Try
}// --- END onPostExecute
}// --- END UILJSONParse Class
I've figured this out since asking the question. I have a Button Interface Activity where an AsyncTask is called that grabs the JSON data when a button is clicked. The AysncTask then bundles the data and sends it to my Gallery Grid Class. The AsyncTask is calling the above JSON Parsing Class. So here's the code:
// --- artwork button
cartoon_BTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
jsonFileStr = "artwork_json";
new ArtworkJSON().execute();
}
});
// --- end artwork button
private class ArtworkJSON extends AsyncTask<Void, Void, Void> {
JSONObject jsonobject;
String TAG_ID = "id";
String TAG_DESCR = "artworkdescr";
String TAG_MEDIUM = "artworkmedium";
String TAG_PRICE = "artworkprice";
String TAG_URL = "artworkurl";
ArrayList<HashMap<String, String>> hashArraylist;
ArrayList<String> urlArrayList;
ArrayList<String> idArrayList;
ArrayList<String> descrArrayList;
ArrayList<String> mediumArrayList;
ArrayList<String> priceArrayList;
String[] idStrArray, urlStrArray, descrStrArray, mediumStrArray,
priceStrArray;
String urlPathStr = "http://www.mysite.com/"
+ jsonFileStr + ".txt";
JSONArray JSArrArtwork = null;
String idStr, urlStr, descrStr, mediumStr, priceStr;
ProgressDialog loadImagesDia;
Intent bundleIn;
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
loadImagesDia = new ProgressDialog(Main_Interface.this);
loadImagesDia.setMessage("Loading Images...");
loadImagesDia.setIndeterminate(false);
// Show progressdialog
loadImagesDia.show();
}
#Override
protected Void doInBackground(Void... params) {
hashArraylist = new ArrayList<HashMap<String, String>>();//
// Retrieve JSON Objects from the given URL address
jsonobject = JSONforGallery.getJSONfromURL(urlPathStr);
try {
// Locate the array name in JSON
JSArrArtwork = jsonobject.getJSONArray("artwork");
idArrayList = new ArrayList<String>();
urlArrayList = new ArrayList<String>();
descrArrayList = new ArrayList<String>();
mediumArrayList = new ArrayList<String>();
priceArrayList = new ArrayList<String>();
for (int i = 0; i < JSArrArtwork.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();//
JSONObject artworkJO = JSArrArtwork.getJSONObject(i);
map.put("id", artworkJO.getString(TAG_ID));//
map.put("url", artworkJO.getString(TAG_URL));//
map.put("descr", artworkJO.getString(TAG_DESCR));//
map.put("medium", artworkJO.getString(TAG_MEDIUM));//
map.put("price", artworkJO.getString(TAG_PRICE));//
idStr = artworkJO.getString(TAG_ID);
urlStr = artworkJO.getString(TAG_URL);
descrStr = artworkJO.getString(TAG_DESCR);
mediumStr = artworkJO.getString(TAG_MEDIUM);
priceStr = artworkJO.getString(TAG_PRICE);
hashArraylist.add(map);//
idArrayList.add(idStr);
urlArrayList.add(urlStr);
descrArrayList.add(descrStr);
mediumArrayList.add(mediumStr);
priceArrayList.add(priceStr);
idStrArray = idArrayList.toArray(new String[idArrayList
.size()]);
urlStrArray = urlArrayList.toArray(new String[urlArrayList
.size()]);
descrStrArray = descrArrayList
.toArray(new String[descrArrayList.size()]);
mediumStrArray = mediumArrayList
.toArray(new String[mediumArrayList.size()]);
priceStrArray = priceArrayList
.toArray(new String[priceArrayList.size()]);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
loadImagesDia.dismiss();
bundleIn = new Intent("com.veedabugmedia.ktg.UILGRID");
bundleIn.putExtra("idStrArrayKey", idStrArray);
bundleIn.putExtra("hashARKey", hashArraylist);
bundleIn.putExtra("urlStrArrayKey", urlStrArray);
bundleIn.putExtra("descrStrArrayKey", descrStrArray);
bundleIn.putExtra("mediumStrArrayKey", mediumStrArray);
bundleIn.putExtra("priceStrArrayKey", priceStrArray);
startActivity(bundleIn);
}
}
My updated UILGrid Activity:
public class UILGrid extends AbsListViewBaseActivity {
String[] idStr, imageUrls, descrStrGrid, mediumStrGrid, priceStrGrid;
DisplayImageOptions options;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.uil_grid);
// Retrieve data from About_Interface on item click event
Intent getBundsIn = getIntent();
idStr = getBundsIn.getStringArrayExtra("idStrArrayKey");
imageUrls = getBundsIn.getStringArrayExtra("urlStrArrayKey");
descrStrGrid = getBundsIn.getStringArrayExtra("descrStrArrayKey");
mediumStrGrid = getBundsIn.getStringArrayExtra("mediumStrArrayKey");
priceStrGrid = getBundsIn.getStringArrayExtra("priceStrArrayKey");
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_stub)
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error).cacheInMemory(true)
.cacheOnDisc(true).bitmapConfig(Bitmap.Config.RGB_565).build();
listView = (GridView) findViewById(R.id.uil_gridview);
((GridView) listView).setAdapter(new ImageAdapter());
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
startImagePagerActivity(position);
}
});
}// --- END onCreate
private void startImagePagerActivity(int position) {
Intent pagerIn = new Intent(this, UILPager.class);
pagerIn.putExtra("pagerUrlStrKey", imageUrls);
pagerIn.putExtra("pagerDescrStrKey", descrStrGrid);
pagerIn.putExtra("pagerMediumStrKey", mediumStrGrid);
pagerIn.putExtra("pagerPriceStrKey", priceStrGrid);
pagerIn.putExtra("pagerPositionKey", position);
startActivity(pagerIn);
}
public class ImageAdapter extends BaseAdapter {
#Override
public int getCount() {
return imageUrls.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ImageView imageView;
if (convertView == null) {
imageView = (ImageView) getLayoutInflater().inflate(
R.layout.uil_grid_item, parent, false);
} else {
imageView = (ImageView) convertView;
}
imageLoader.displayImage(imageUrls[position], imageView, options);
return imageView;
}
}
#Override
protected void onPause() {
super.onPause();
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
UILGrid.this.finish();
}
}

Pull to refresh GridView infinite loading/ fails to pull data

I can't seem to figure out what is going wrong with this, the code is pretty clean/ simple, but for some reason when I pull to refresh, it just shows me the loading icon infinity. Not only that, but I don't even receive any errors. The library I used for pull to refresh is this one.
I've spent several hours trying to figure this out, but the fact that it's not even giving me errors is making it very hard for me to track down.
And yes, I am sure the rest request is working.
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
public final class PullToRefresh extends Activity {
static final int MENU_SET_MODE = 0;
static final String KEY_FEED = "feed"; // parent node
static final String KEY_UID_FK = "uid_fk";
static final String KEY_FIRST_NAME = "first_name";
static final String KEY_LAST_NAME = "last_name";
public static final String KEY_NAME = "name";
static final String KEY_MESSAGE = "message";
static final String KEY_CREATED = "created";
static final String KEY_THUMB_URL = "thumb_img";
static final String KEY_DATA = "data";
static final String KEY_HOMETOWN = "hometown";
static final String KEY_BIO = "bio";
private ArrayList<HashMap<String, String>> feedList = new ArrayList<HashMap<String, String>>();
private PullToRefreshGridView mPullRefreshGridView;
private GridView mGridView;
private GridAdapter adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ptr_grid);
mPullRefreshGridView = (PullToRefreshGridView) findViewById(R.id.pull_refresh_grid);
mGridView = mPullRefreshGridView.getRefreshableView();
// Set a listener to be invoked when the list should be refreshed.
mPullRefreshGridView
.setOnRefreshListener(new OnRefreshListener2<GridView>() {
#Override
public void onPullDownToRefresh(
PullToRefreshBase<GridView> refreshView) {
Toast.makeText(PullToRefresh.this, "Pull Down!",
Toast.LENGTH_SHORT).show();
try {
new RestClientUsage().getPublicTimeline();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onPullUpToRefresh(
PullToRefreshBase<GridView> refreshView) {
Toast.makeText(PullToRefresh.this, "Pull Up!",
Toast.LENGTH_SHORT).show();
try {
new RestClientUsage().getPublicTimeline();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
ArrayList<HashMap<String, String>> feedList = new ArrayList<HashMap<String, String>>();
TextView tv = new TextView(this);
tv.setGravity(Gravity.CENTER);
tv.setText("Empty View, Pull Down/Up to Add Items");
mPullRefreshGridView.setEmptyView(tv);
adapter = new GridAdapter(PullToRefresh.this, feedList);
mGridView.setAdapter(adapter);
}
class RestClientUsage {
public void getPublicTimeline() throws JSONException {
RequestParams params = new RequestParams();
params.put("loggedin_uid", TabHostFragmentActivity.loggedin_uid);
RestClient.post("http://localhost/basic/rest/request/format/json",
params, new JsonHttpResponseHandler() {
private JSONArray feed;
#Override
public void onSuccess(JSONObject json) {
try {
Log.i("JSON->TRAILS RESPONSE", json.toString(3));
// Getting Feed Array
feed = json.getJSONArray(KEY_FEED);
/*
* Log & Debug Code String feed_log =
* feed.toString(3); int feed_length =
* feed.length(); String string_length =
* Integer.toString(feed_length);
* Log.i("JSON PROFILE FEED RESPONSE", feed_log
* ); Log.i("JSON PROFILE FEED LENGTH",
* string_length);
*/
// looping through Feed of Updates
for (int i = 0; i < feed.length(); i++) {
JSONObject c = feed.getJSONObject(i);
String jFeedObj = c.toString(3);
Log.i("JSON FEED OBJ", jFeedObj);
// Storing each json item in variable
String uid = c.getString(KEY_UID_FK);
String first_name = c
.getString(KEY_FIRST_NAME);
String last_name = c
.getString(KEY_LAST_NAME);
String name = first_name + ' ' + last_name;
String http = "http://10.0.2.2/CI_REST_LOGIN/UPLOADS/thumbs/";
String base_url = c
.getString(KEY_THUMB_URL);
String thumb_url = http + base_url;
String message = c.getString(KEY_MESSAGE);
String created = c.getString(KEY_CREATED);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key =>
// value
map.put(KEY_UID_FK, uid);
map.put(KEY_NAME, name);
map.put(KEY_MESSAGE, message);
map.put(KEY_CREATED, created);
map.put(KEY_THUMB_URL, thumb_url);
Log.i("Trails - line 130", "Success");
// adding HashList to ArrayList
feedList.add(map);
}
adapter.notifyDataSetChanged();
// Call onRefreshComplete when the list has been
// refreshed.
mPullRefreshGridView.onRefreshComplete();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(
0,
MENU_SET_MODE,
0,
mPullRefreshGridView.getMode() == Mode.BOTH ? "Change to MODE_PULL_DOWN"
: "Change to MODE_PULL_BOTH");
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem setModeItem = menu.findItem(MENU_SET_MODE);
setModeItem
.setTitle(mPullRefreshGridView.getMode() == Mode.BOTH ? "Change to MODE_PULL_FROM_START"
: "Change to MODE_PULL_BOTH");
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_SET_MODE:
mPullRefreshGridView
.setMode(mPullRefreshGridView.getMode() == Mode.BOTH ? Mode.PULL_FROM_START
: Mode.BOTH);
break;
}
return super.onOptionsItemSelected(item);
}
}
And here is the code for my GridView adapter:
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.loopj.android.image.SmartImageView;
public class GridAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
public GridAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.mobile, null);
TextView name = (TextView) vi.findViewById(R.id.grid_item_label); // title
SmartImageView thumb_image = (SmartImageView) vi
.findViewById(R.id.grid_item_image);
HashMap<String, String> update = new HashMap<String, String>();
update = data.get(position);
// Setting all values in listview
name.setText(update.get("name"));
thumb_image.setImageUrl(update.get("thumb_img"));
name.setOnClickListener(new myOnClickListener(position));
thumb_image.setOnClickListener(new myOnClickListener(position));
return vi;
}
public class myOnClickListener implements OnClickListener {
private int position;
private String clicked_uid;
public myOnClickListener(int position) {
this.position = position;
}
#Override
public void onClick(View v) { // TODO Auto-generated method stub
HashMap<String, String> update = new HashMap<String, String>();
update = data.get(position);
Log.i("Update Position:", update.toString());
clicked_uid = update.get("uid");
Log.d("Clicked UID:", clicked_uid + "");
Intent i = new Intent(activity.getApplicationContext(),
TabHostFragmentActivity.class);
i.putExtra("profile_uid", clicked_uid);
activity.startActivity(i);
}
}
}
You should POST to 10.0.2.2 instead of localhost in the call to RestClient.post in RestClientUsage.
I am not familiar withJsonHttpResponseHandler, but I would image there's an onFailure method (or something similar) that you may want to override. If there is, you may way to call mPullRefreshGridView.onRefreshComplete() in it.

updating onlistitemclick listview from async just really confused

Ok this is my first every android app so don't bash me. I am very open to suggestion if I am doing anything wrong or weird so please don't be shy. I'm have a little bit of trouble updating my listview after I click on an item. Anyways here's the code... I just don't understand how it works I think...
[ MainActivity.java ]
package com.mycompany.myapp2;
import android.app.*;
import android.os.*;
import android.text.method.*;
import android.view.*;
import android.widget.*;
import android.content.*;
import java.util.*;
import java.io.*;
public class MainActivity extends ListActivity
{
public CustomAdapter adapterMain;
private FtpConnectionTask ftpTask;
private LayoutInflater mInflater;
private Vector<RowData> data;
private TextView textView;
#Override
public void onCreate( Bundle savedInstanceState )
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView = (TextView) findViewById(R.id.txtView);
textView.setMovementMethod(new ScrollingMovementMethod());
xBins(textView);
}
/*public void addItems( ListView parent )
{
CustomAdapter adapter = (CustomAdapter) parent.getAdapter();
RowData rd = new RowData("item4", "description4");
data.add(rd);
rd = new RowData("item5", "description5");
data.add(rd);
rd = new RowData("item6", "description6");
data.add(rd);
CustomAdapter adapter = new CustomAdapter(this, R.layout.row, R.id.item, data);
setListAdapter(adapter);
getListView().setTextFilterEnabled(true);
}*/
public void onListItemClick( ListView parent, View v, int position, long id )
{
ftpTask.row = ftpTask.adapter.getItem(position);
String ftpItem = ftpTask.row.mItem;
if ( ftpTask.row.mDescription == "dir" )
{
String[] args = new String[] { ftpItem };
Object[] aObject = new Object[] { "cd", args, this };
//ftpTask.adapter.clear();
//ftpTask.processCmd(aObject);
}
}
private class RowData
{
protected String mItem;
protected String mDescription;
RowData( String item, String description )
{
mItem = item;
mDescription = description;
}
#Override
public String toString( )
{
return mItem + " " + mDescription;
}
}
private class CustomAdapter extends ArrayAdapter<RowData>
{
public CustomAdapter( Context context, int resource,
int textViewResourceId, List<RowData> objects )
{
super(context, resource, textViewResourceId, objects);
}
#Override
public View getView( int position, View convertView, ViewGroup parent )
{
ViewHolder holder = null;
//widgets displayed by each item in your list
TextView item = null;
TextView description = null;
//data from your adapter
RowData rowData= getItem(position);
//we want to reuse already constructed row views...
if ( null == convertView )
{
convertView = mInflater.inflate(R.layout.row, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
//
holder = (ViewHolder) convertView.getTag();
item = holder.getItem();
item.setText(rowData.mItem);
description = holder.getDescription();
description.setText(rowData.mDescription);
return convertView;
}
}
/**
* Wrapper for row data.
*
*/
private class ViewHolder
{
private View mRow;
private TextView description = null;
private TextView item = null;
public ViewHolder( View row )
{
mRow = row;
}
public TextView getDescription( )
{
if ( null == description )
{
description = (TextView) mRow.findViewById(R.id.description);
}
return description;
}
public TextView getItem( )
{
if ( null == item )
{
item = (TextView) mRow.findViewById(R.id.item);
}
return item;
}
}
public void xBins( View view )
{
IrcConnectionTask task = new IrcConnectionTask();
task.execute(new Object[] { "irc.efnet.pl", 6667, "sgd5", this });
}
}
[ IrcConnectionTask.java ]
package com.mycompany.myapp2;
import android.os.*;
import java.io.*;
import java.net.*;
public class IrcConnectionTask extends AsyncTask<Object, String, String>
{
MainActivity callerActivity;
private Socket socket;
#Override
protected String doInBackground(Object... params)
{
String response = "";
String host = (String)params[0];
Integer port = (Integer)(params[1]);
String nick = (String)params[2];
callerActivity = (MainActivity)params[3];
try
{
socket = new Socket(host, port);
String msg1 = "NICK " + nick;
String msg2 = "USER sur 8 * :be";
String messages[] = { msg1, msg2 };
InputDumper task = new InputDumper();
task.execute(new Object[] { socket, messages, nick, callerActivity});
}
catch ( UnknownHostException e )
{
e.printStackTrace();
}
catch ( IOException e )
{
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String result)
{
//textView.setText(result);
}
#Override
protected void onProgressUpdate(String result)
{
//textView.setText(result);
}
}
[ InputDumper.java ]
package com.mycompany.myapp2;
import android.os.*;
import android.text.*;
import java.io.*;
import java.net.*;
import android.widget.*;
public class InputDumper extends AsyncTask<Object, String, String>
{
MainActivity callerActivity;
private String response = "";
private Integer i = 0;
private Boolean Connected = false;
protected String doInBackground(Object... params)
{
try
{
Socket socket = (Socket)params[0];
String messages[] = (String[])params[1];
String nickname = (String)params[2];
callerActivity = (MainActivity) params[3];
//Pattern pattern = Pattern.compile("USERNAME: (.*)");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String msg;
while ((msg = bufferedReader.readLine()) != null)
{
if (msg.indexOf("USERNAME:") > 0)
{
new FtpConnectionTask().execute(new Object[] { nickname, "emulation", callerActivity });
publishProgress("FTP CONNECTION STARTED!!!");
}
if (msg.startsWith("PING"))
{
String PONG = "PONG " + msg.substring(msg.indexOf(":"));
new OutputWriter().execute(new Object[] { socket, PONG, callerActivity });
Connected = true;
}
else if (i == 4)
{
for (String message : messages)
{
new OutputWriter().execute(new Object[] { socket, message, callerActivity });
}
}
else if (i == 13) //msg.endsWith("servers"))
{
new OutputWriter().execute(new Object[] { socket, "JOIN #xbins", callerActivity });
}
else if (i == 20)
{
new OutputWriter().execute(new Object[] { socket, "PRIVMSG #xbins :!list", callerActivity });
}
response += msg;
publishProgress(msg);
i++;
}
}
catch (IOException e )
{
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String result)
{
//textView.setText(result);
}
private TextView textView;
#Override
protected void onProgressUpdate(String... progress)
{
textView = (TextView) callerActivity.findViewById(R.id.txtView);
textView.append(Html.fromHtml("<font color='green'>" + progress[0] + "</font><br />"));
final int scrollAmount = textView.getLayout().getLineTop(textView.getLineCount())
- textView.getHeight();
// if there is no need to scroll, scrollAmount will be <=0
if (scrollAmount > 0)
textView.scrollTo(0, scrollAmount);
else
textView.scrollTo(0, 0);
}
}
[ OutputWriter.java ]
package com.mycompany.myapp2;
import android.os.*;
import android.text.*;
import java.io.*;
import java.net.*;
import android.widget.*;
public class OutputWriter extends AsyncTask<Object, String, String>
{
MainActivity callerActivity;
private String response = "";
protected String doInBackground(Object... params)
{
try
{
Socket socket = (Socket)params[0];
String message = (String)params[1];
callerActivity = (MainActivity)params[2];
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bufferedWriter.write(message + "\n\r");
bufferedWriter.flush();
publishProgress(message);
}
catch (IOException e )
{
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String result)
{
//textView.setText(result);
}
private TextView textView;
#Override
protected void onProgressUpdate(String... progress)
{
textView = (TextView) callerActivity.findViewById(R.id.txtView);
textView.append(Html.fromHtml("<font color='red'>" + progress[0] + "</font><br />"));
final int scrollAmount = textView.getLayout().getLineTop(textView.getLineCount())
- textView.getHeight();
// if there is no need to scroll, scrollAmount will be <=0
if (scrollAmount > 0)
textView.scrollTo(0, scrollAmount);
else
textView.scrollTo(0, 0);
}
}
[ FtpConnectionTask.java ]
package com.mycompany.myapp2;
import android.os.*;
import android.text.*;
import android.util.*;
import android.widget.*;
import java.io.*;
import org.apache.commons.io.*;
import org.apache.commons.net.ftp.*;
import java.util.*;
import android.view.*;
import android.content.*;
import android.app.*;
public class FtpConnectionTask extends AsyncTask<Object, String, String>
{
public static CustomAdapter adapter;
public static RowData row;
MainActivity callerActivity;
private LayoutInflater mInflater;
public Vector<RowData> data;
private FTPClient mFTPClient = new FTPClient();
protected String doInBackground( Object... params )
{
try
{
if ( mFTPClient.isConnected() )
{
Log.v("TESTING", "Is connected");
String cmd = (String)params[0];
String[] args = (String[])params[1];
callerActivity = (MainActivity) params[2];
if (cmd == "cd")
{
mFTPClient.changeWorkingDirectory(args[0].toString());
String[] names = mFTPClient.listNames();
listRemote(names);
}
}
else
{
String user = (String)params[0];
String pass = (String)params[1];
callerActivity = (MainActivity) params[2];
mFTPClient.connect("distribution.xbins.org");
mFTPClient.login(user, pass);
mFTPClient.enterLocalActiveMode();
mFTPClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);
mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
publishProgress("WORKING DIR: " + mFTPClient.printWorkingDirectory());
publishProgress("LOGGED IN");
String[] names = mFTPClient.listNames();
listRemote(names);
FTPFile[] remoteFiles = mFTPClient.listFiles();
for ( FTPFile remoteFile : remoteFiles ) //int i = 0; i < remoteFiles.length; i++)
{
if ( remoteFile.getType() == FTPFile.FILE_TYPE )
{
String name = remoteFile.getName();
long length = remoteFile.getSize();
String readableLength = FileUtils.byteCountToDisplaySize(length);
publishProgress(name + ":\t\t" + readableLength);
}
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
final void listRemote(final String... params)
{
callerActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
mInflater = (LayoutInflater) callerActivity.getSystemService(callerActivity.LAYOUT_INFLATER_SERVICE);
data = new Vector<RowData>();
for ( String name : params )
{
row = new RowData(name, "dir");
data.add(row);
}
adapter = new CustomAdapter(callerActivity, R.layout.row, R.id.item, data);
callerActivity.setListAdapter(adapter);
callerActivity.getListView().setTextFilterEnabled(true);
}
});
}
private TextView textView;
#Override
protected void onProgressUpdate( String... progress )
{
textView = (TextView) callerActivity.findViewById(R.id.txtView);
textView.append(Html.fromHtml("<font color='yellow'>" + progress[0] + "</font><br />"));
final int scrollAmount = textView.getLayout().getLineTop(textView.getLineCount())
- textView.getHeight();
// if there is no need to scroll, scrollAmount will be <=0
if ( scrollAmount > 0 )
textView.scrollTo(0, scrollAmount);
else
textView.scrollTo(0, 0);
}
public class RowData
{
protected String mItem;
protected String mDescription;
RowData( String item, String description )
{
mItem = item;
mDescription = description;
}
#Override
public String toString( )
{
return mItem + " " + mDescription;
}
}
public class CustomAdapter extends ArrayAdapter<RowData>
{
public CustomAdapter( Context context, int resource,
int textViewResourceId, List<RowData> objects )
{
super(context, resource, textViewResourceId, objects);
}
#Override
public View getView( int position, View convertView, ViewGroup parent )
{
ViewHolder holder = null;
//widgets displayed by each item in your list
TextView item = null;
TextView description = null;
//data from your adapter
RowData rowData= getItem(position);
//we want to reuse already constructed row views...
if ( null == convertView )
{
convertView = mInflater.inflate(R.layout.row, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
//
holder = (ViewHolder) convertView.getTag();
item = holder.getItem();
item.setText(rowData.mItem);
description = holder.getDescription();
description.setText(rowData.mDescription);
return convertView;
}
}
/**
* Wrapper for row data.
*
*/
public class ViewHolder
{
private View mRow;
private TextView description = null;
private TextView item = null;
public ViewHolder( View row )
{
mRow = row;
}
public TextView getDescription( )
{
if ( null == description )
{
description = (TextView) mRow.findViewById(R.id.description);
}
return description;
}
public TextView getItem( )
{
if ( null == item )
{
item = (TextView) mRow.findViewById(R.id.item);
}
return item;
}
}
}
[ row.xml]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#00000000">
<TextView
android:id="#+id/item"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:focusableInTouchMode="false"
android:clickable="false"
android:focusable="false"/>
<TextView
android:id="#+id/description"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:focusableInTouchMode="false"
android:clickable="false"
android:focusable="false" />
</LinearLayout>
[ main.xml ]
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
android:id="#+id/txtView"
android:maxLines = "5"
android:scrollbars = "vertical" />
<ListView
android:id="#android:id/list"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:layout_below="#+id/txtView" />
</RelativeLayout>

Categories

Resources