This problem has bothered me for a long time. I use a cloud database called bmob, and I found that I can successfully get the data I want. However, there might be some mistakes in the loops, and I could only get the information of the last selected item.
p.s. I use an array list called Playlist to store the calculated data that I will use to display a list-view in the next activity.
here is my code:
public class DestinationActivity extends Activity implements OnClickListener, NumberPicker.OnValueChangeListener {
private TextView from_place, date, days, start_time, end_time, number, money_view;
private Button addButton, subButton;
private ImageView backButton, telephone;
private ListView listView;
private Button destinationOk_btn;
private ShapeLoadingDialog shapeLoadingDialog;
private Tip startTip;
private Calendar calendar;
private DatePickerDialog dialog;
private TimePickerDialog dialog2;
private List<Destination> destinationList = new ArrayList<Destination>();
private DestinationAdapter adapter;
private int number_value = 1;
private String time_start;
private String time_end;
private int travel_days;
double travelTime;//total playing time
double travel_time;
private int money;
private int num = 1;
private ArrayList<Integer> select_placeID = new ArrayList<Integer>();
public Map<Integer,Double> weightMap;
public List<Plan> planList = new ArrayList<Plan>();
int[] selectedID = new int[10];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.destination_layout);
//initialize the cloud database
Bmob.initialize(this, BmobConfig.APP_ID);
listView = (ListView) findViewById(R.id.list_destination);
destinationOk_btn = (Button) findViewById(R.id.okButton);
initDestinations(); // initialize the data
adapter = new DestinationAdapter(destinationList, DestinationActivity.this);
//adapter = new DestinationAdapter(this, destinationList, DestinationAdapter.getIsSelected());
listView.setAdapter(adapter);
//....listeners and textviews.......
//submit button
destinationOk_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
select_placeID.clear();
for (int i = 0; i < destinationList.size(); i++) {
if (DestinationAdapter.getIsSelected().get(i)) {
select_placeID.add((i + 1));
}
}
//change to int array
selectedID = new int[select_placeID.size()];
for(int i = 0;i<select_placeID.size();i++){
selectedID[i] = select_placeID.get(i);
}
if (select_placeID.size() == 0) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(DestinationActivity.this);
builder1.setMessage("no records");
builder1.show();
}
else {
AlertDialog.Builder builder = new AlertDialog.Builder(DestinationActivity.this);
builder.setMessage("waiting for magic...");
builder.show();
/**
* calculate the route
*/
if (validate()) {
new calRoute().execute();
}
}
}
});
}
//initialize the data
private void initDestinations() {
//........
}
#Override
public void onClick(View v) {
//.......
}
/**
* asynctask
*/
private class calRoute extends AsyncTask<Void, Void, List<Plan>>{
public calRoute(){
// TODO Auto-generated constructor stub
}
#Override
protected List<Plan> doInBackground(Void... params) {
List<Plan> result = calculate(time_start, time_end, travel_days);
return result;
}
#Override
protected void onPostExecute(List<Plan> result) {
super.onPostExecute(result);
if (result != null) {
Toast.makeText(DestinationActivity.this, "success", Toast.LENGTH_SHORT).show();
if(planList.size() > 0) {
Intent intent = new Intent();
intent.setClass(DestinationActivity.this, ActivityPlan.class);
intent.putParcelableArrayListExtra("planInfo", (ArrayList<? extends Parcelable>) planList);
startActivity(intent);
}
else{
Toast.makeText(DestinationActivity.this, "no plan", Toast.LENGTH_SHORT).show();
}
}
}
}
/**
*plan
**/
public List<Plan> calculate(String time_start, String time_end, int travel_days) {
SimpleDateFormat df = new SimpleDateFormat(("HH:mm"));
Date starttime = new Date();
Date endtime = new Date();
try {
starttime = df.parse(time_start);
} catch (ParseException e) {
e.printStackTrace();
}
try {
endtime = df.parse(time_end);
} catch (ParseException e) {
e.printStackTrace();
}
double l = endtime.getTime() - starttime.getTime();
double hour = (l / (60 * 60 * 1000));
double min = ((l / (60 * 1000)) - hour * 60);
if(min == 0){
min = 60;
}
else {
travel_time = ((1.0 * travel_days * hour) * (min / 60));
DecimalFormat decimalFormat = new DecimalFormat("#.0");
travelTime = Double.parseDouble(decimalFormat.format(travel_time));
}
weightMap = new LinkedHashMap<Integer, Double>(); //store weight
int totalPriority = 0;//total priority
final Destination start = new Destination(116.32133, 39.92269);
final HashMap<Integer, Integer> pMap = new HashMap<Integer, Integer>();
final HashMap<Integer, String> nameMap = new HashMap<Integer, String>();
final HashMap<Integer, Destination> objectMap = new LinkedHashMap<Integer, Destination>();
/**
* get the data from cloud database
*/
BmobQuery<Destination> query = new BmobQuery<Destination>();
for (int sid: selectedID) {
query.addWhereEqualTo("id", sid);
query.findObjects(new FindListener<Destination>() {
#Override
public void done(List<Destination> list, BmobException e) {
if (e == null) {
System.out.println("success:total" + list.size() + "items。");
for (Destination destination : list) {
int p = destination.getPriority();
int id = destination.getId();
String name = destination.getName();
double longitude = destination.getLongitude();
double latitude = destination.getLatitude();
objectMap.put(id, new Destination(longitude, latitude));
System.out.println(id);
double dis = DistanceUtil.distance(start.getLongitude(), start.getLatitude(),
longitude, latitude);
pMap.put(id, p);
weightMap.put(id, new Double(dis));
nameMap.put(id, name);
}
} else {
Log.i("bmob", "error:" + e.getMessage() + "," + e.getErrorCode());
}
}
});
}
for (Integer key : pMap.keySet()) {
int p = pMap.get(key).intValue();
totalPriority = totalPriority + p;
}
double weight = 0.0;
for (Map.Entry<Integer, Double> hm : weightMap.entrySet()) {
double hm2Value = pMap.get(hm.getKey());
weight = totalPriority / hm.getValue() * hm2Value;
weightMap.put(hm.getKey(), weight);
}
/**
* 按照weight值来排序
* 判断是否传递数据给plan_activity
*/
MapUtil.sortByValue(weightMap);
//排好序后计算距离
Iterator it = weightMap.entrySet().iterator();
int order = 0;
while (it.hasNext()) {
order++;
Map.Entry entry = (Map.Entry) it.next();
objectMap.put(new Integer(order), objectMap.get(entry.getKey()));
}
PlanTask planTask = new PlanTask();//封装了每个plan计算的方法
for (Map.Entry<Integer, Double> entry : weightMap.entrySet()) {
System.out.println("id= " + entry.getKey());
double play_time = planTask.calPlay_time(weightMap.size(),
weightMap.get(entry.getKey()), travelTime);
double driving_time = planTask.calDrive_time(DistanceUtil.distance(
objectMap.get(entry.getKey()).getLatitude(),
objectMap.get(entry.getKey()).getLongitude(),
objectMap.get(entry.getKey() + 1).getLatitude(),
objectMap.get(entry.getKey() + 1).getLongitude()
));
String arrive_time = "hello world";//未完待续
String place_name = nameMap.get(entry.getKey());
Plan plan = new Plan(place_name, arrive_time, driving_time, play_time);
//传递plan对象list
planList.add(entry.getKey(), plan);
}
return planList;
}
}
When I debug it, I found that in calculate() functions, the output of
BmobQuery<Destination> query = new BmobQuery<Destination>();
for (int sid: selectedID) {
query.addWhereEqualTo("id", sid);
query.findObjects(new FindListener<Destination>() {
#Override
public void done(List<Destination> list, BmobException e) {
if (e == null) {
System.out.println("success:total" + list.size() + "items。");
for (Destination destination : list) {
int p = destination.getPriority();
int id = destination.getId();
String name = destination.getName();
double longitude = destination.getLongitude();
double latitude = destination.getLatitude();
objectMap.put(id, new Destination(longitude, latitude));
System.out.println(id);
//calculate the distance
double dis = DistanceUtil.distance(start.getLongitude(), start.getLatitude(),
longitude, latitude);
pMap.put(id, p);
weightMap.put(id, new Double(dis));
nameMap.put(id, name);
}
} else {
Log.i("bmob", "error:" + e.getMessage() + "," + e.getErrorCode());
}
}
});
is "success:total 1 items." and after the loop, if I have selected 3 items, it would be "success:total 1 items." for 3 times and only the information of the last item is caught.
AND the size of three hash map: pMap, nameMap and objectMap are all zero. Why is it??? It is so strange...
There is no error in LogCAT, however, the ordered list view cannot display in the second activity. PLEASE help me, it has bothered me for a long time.
Thank you!!!
I couldn't figure out much unfortunately, since I am not really comfortable with reactive programming yet as the platform uses a lot of rxjava in general, but here is something that would enhance the code a little bit
final HashMap<Integer, Integer> pMap = new HashMap<Integer, Integer>();
final HashMap<Integer, String> nameMap = new HashMap<Integer, String>();
final HashMap<Integer, Destination> objectMap = new LinkedHashMap<Integer, Destination>();
/**
* get the data from cloud database
*/
BmobQuery<Destination> query = new BmobQuery<Destination>();
// this time only one list of three elements is added instead of three lists of one element each
query.addWhereContainedIn("id", Arrays.asList(selectedID));
query.findObjects(new FindListener<Destination>() {
#Override
public void done(List<Destination> list, BmobException e) {
if (e == null) {
System.out.println("success:total" + list.size() + "items。");
for (Destination destination : list) {
int p = destination.getPriority();
int id = destination.getId();
String name = destination.getName();
double longitude = destination.getLongitude();
double latitude = destination.getLatitude();
objectMap.put(id, new Destination(longitude, latitude));
System.out.println(id);
//calculate the distance
double dis = DistanceUtil.distance(start.getLongitude(), start.getLatitude(),
longitude, latitude);
pMap.put(id, p);
weightMap.put(id, new Double(dis));
nameMap.put(id, name);
}
// continue execution here though you won't be able to return a list of plans here
} else {
Log.i("bmob", "error:" + e.getMessage() + "," + e.getErrorCode());
}
}
});
Hope this helps :)
List<HashMap<Integer, Destination>> listmap=new ArrayList<>;
final HashMap<Integer, Destination> objectMap;
/**
* get the data from cloud database
*/
BmobQuery<Destination> query = new BmobQuery<Destination>();
// this time only one list of three elements is added instead of three lists of one element each
query.addWhereContainedIn("id", Arrays.asList(selectedID));
query.findObjects(new FindListener<Destination>() {
#Override
public void done(List<Destination> list, BmobException e) {
if (e == null) {
System.out.println("success:total" + list.size() + "items。");
for (Destination destination : list) {
objectMap = new LinkedHashMap<Integer, Destination>();
int id = destination.getId();
objectMap.put(id, destination);
listmap.add(objectMap);
}
// continue execution here though you won't be able to return a list of plans here
} else {
Log.i("bmob", "error:" + e.getMessage() + "," + e.getErrorCode());
}
}
Try this
Related
I'm using an asynchronus library to get the weather forecast, but my code still goes on even if I haven't receive the informations about the weather. Is there any way to wait for the answer ? Or do you know anything that could help me with that ?
The code goes on is fine. You should using callback to receive data. For more detail, please attach your function.
WeatherClass.java
public class WeatherClass {
private static double temp = 0.0;
public static double getTemp(double latitude, double longitude, Context context){
String OPEN_WEATHER_MAP_API = "xxxxxxxxx";
new WeatherManager(OPEN_WEATHER_MAP_API).getFiveDayForecastByCoordinates(latitude,longitude,
new WeatherManager.ForecastHandler() {
#Override
public void onReceivedForecast(WeatherManager manager, Forecast forecast) {
// Handle forecast
List<Double> list = new ArrayList<>();
for (int i = 0; i < 5; i++) {
long timestamp = forecast.getTimestampByIndex(i+3);
Weather weatherForTimestamp = forecast.getWeatherForTimestamp(timestamp);
Temperature tempMini = weatherForTimestamp.getTemperature().getMinimum();
double temperatureInCelcius = tempMini.getValue(TemperatureUnit.CELCIUS);
list.add(temperatureInCelcius);
Log.v("Weather", "" +weatherForTimestamp.getWind().getSpeed());
Log.v("Weather", "Température mini : " + " "+ list.get(i));
}
int minIndex = list.indexOf(Collections.min(list));
Log.v("Weather MINI", "Température mini : " + list.get(minIndex));
//Toast.makeText(context, "Température mini: " + list.get(minIndex), Toast.LENGTH_LONG).show();
temp = list.get(minIndex);
Log.v("WeatherClass", temp + "");
}
#Override
public void onFailedToReceiveForecast(WeatherManager manager) {
Log.v("TAG", " ERREUR");
temp = -1000000;
}
}
);
return temp;
}
}
Your code run:
Create a request to get data.
Return temp = 0.0
Receive data from server and update temp.
So you run your code will get return value = 0.0.
To fix it, you can do:
Create new Interface.
IResult.java
public interface IResult {
void onResult(double temp);
}
Update getTemp method:
public static void getTemp(double latitude, double longitude, final IResult callback){
String OPEN_WEATHER_MAP_API = "xxxxxxxxx";
new WeatherManager(OPEN_WEATHER_MAP_API)
.getFiveDayForecastByCoordinates(latitude,longitude,
new WeatherManager.ForecastHandler() {
#Override
public void onReceivedForecast(WeatherManager manager, Forecast forecast) {
// Handle forecast
List<Double> list = new ArrayList<>();
for (int i = 0; i < 5; i++) {
long timestamp = forecast.getTimestampByIndex(i+3);
Weather weatherForTimestamp = forecast.getWeatherForTimestamp(timestamp);
Temperature tempMini = weatherForTimestamp.getTemperature().getMinimum();
double temperatureInCelcius = tempMini.getValue(TemperatureUnit.CELCIUS);
list.add(temperatureInCelcius);
Log.v("Weather", "" +weatherForTimestamp.getWind().getSpeed());
Log.v("Weather", "Température mini : " + " "+ list.get(i));
}
int minIndex = list.indexOf(Collections.min(list));
Log.v("Weather MINI", "Température mini : " + list.get(minIndex));
//Toast.makeText(context, "Température mini: " + list.get(minIndex), Toast.LENGTH_LONG).show();
temp = list.get(minIndex);
Log.v("WeatherClass", temp + "");
callback.onResult(temp);
}
#Override
public void onFailedToReceiveForecast(WeatherManager manager) {
Log.v("TAG", " ERREUR");
temp = -1000000;
callback.onResult(temp);
}
}
);
}
Use it
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WeatherClass.getTemp(32.32, 322.3, new IResult() {
#Override
public void onResult(double temp) {
//result here
}
});
}
Update: Because the first launch, this method return 0.0 before updating temp (step 2 return temp, step 3 update temp), so you will get 0.0. The second launch, this method will return the result of first launch (because it return temp before updating temp), so you may think it right (but not right, return value is data of the first launch) .
when i click + button increment the price and click - button decrease the price it's work perfectly but when i scroll listview the value of tvPrices (TextView) is changed.
What should i do for the stay increment price?
here is my adapter
public class ListAdapter extends BaseAdapter {
public ArrayList<Integer> quantity = new ArrayList<Integer>();
public ArrayList<Integer> price = new ArrayList<Integer>();
private String[] listViewItems, prices, static_price;
TypedArray images;
View row = null;
static String get_price, get_quntity;
int g_quntity, g_price, g_minus;
private Context context;
CustomButtonListener customButtonListener;
static HashMap<String, String> map = new HashMap<>();
public ListAdapter(Context context, String[] listViewItems, TypedArray images, String[] prices) {
this.context = context;
this.listViewItems = listViewItems;
this.images = images;
this.prices = prices;
for (int i = 0; i < listViewItems.length; i++) {
quantity.add(0);
price.add(0);
}
}
public void setCustomButtonListener(CustomButtonListener customButtonListner) {
this.customButtonListener = customButtonListner;
}
#Override
public int getCount() {
return listViewItems.length;
}
#Override
public String getItem(int position) {
return listViewItems[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ListViewHolder listViewHolder;
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.activity_custom_listview, parent, false);
listViewHolder = new ListViewHolder();
listViewHolder.tvProductName = (TextView) row.findViewById(R.id.tvProductName);
listViewHolder.ivProduct = (ImageView) row.findViewById(R.id.ivproduct);
listViewHolder.tvPrices = (TextView) row.findViewById(R.id.tvProductPrice);
listViewHolder.btnPlus = (ImageButton) row.findViewById(R.id.ib_addnew);
listViewHolder.edTextQuantity = (EditText) row.findViewById(R.id.editTextQuantity);
listViewHolder.btnMinus = (ImageButton) row.findViewById(R.id.ib_remove);
static_price = context.getResources().getStringArray(R.array.Price);
row.setTag(listViewHolder);
} else {
row = convertView;
listViewHolder = (ListViewHolder) convertView.getTag();
}
listViewHolder.ivProduct.setImageResource(images.getResourceId(position, -1));
try {
listViewHolder.edTextQuantity.setText(quantity.get(position) + "");
} catch (Exception e) {
e.printStackTrace();
}
listViewHolder.btnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (customButtonListener != null) {
customButtonListener.onButtonClickListener(position, listViewHolder.edTextQuantity, 1);
quantity.set(position, quantity.get(position) + 1);
price.set(position, price.get(position) + 1);
row.getTag(position);
get_price = listViewHolder.tvPrices.getText().toString();
g_price = Integer.valueOf(static_price[position]);
get_quntity = listViewHolder.edTextQuantity.getText().toString();
g_quntity = Integer.valueOf(get_quntity);
map.put("" + listViewHolder.tvProductName.getText().toString(), " " + listViewHolder.edTextQuantity.getText().toString());
listViewHolder.tvPrices.setText("" + g_price * g_quntity);
// Log.d("A ", "" + a);
// Toast.makeText(context, "A" + a, Toast.LENGTH_LONG).show();
// Log.d("Position ", "" + position);
// System.out.println(+position + " Values " + map.values());
ShowHashMapValue();
listViewHolder.tvPrices.setText("" + g_price * g_quntity);
}
}
});
listViewHolder.btnMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (customButtonListener != null) {
customButtonListener.onButtonClickListener(position, listViewHolder.edTextQuantity, -1);
if (quantity.get(position) > 0)
quantity.set(position, quantity.get(position) - 1);
get_price = listViewHolder.tvPrices.getText().toString();
g_minus = Integer.valueOf(get_price);
g_price = Integer.valueOf(static_price[position]);
int minus = g_minus - g_price;
if (minus >= g_price) {
listViewHolder.tvPrices.setText("" + minus);
}
map.put("" + listViewHolder.tvProductName.getText().toString(), " " + listViewHolder.edTextQuantity.getText().toString());
ShowHashMapValue();
}
}
});
listViewHolder.tvProductName.setText(listViewItems[position]);
listViewHolder.tvPrices.setText(prices[position]);
return row;
}
private void ShowHashMapValue() {
/**
* get the Set Of keys from HashMap
*/
Set setOfKeys = map.keySet();
/**
* get the Iterator instance from Set
*/
Iterator iterator = setOfKeys.iterator();
/**
* Loop the iterator until we reach the last element of the HashMap
*/
while (iterator.hasNext()) {
/**
* next() method returns the next key from Iterator instance.
* return type of next() method is Object so we need to do DownCasting to String
*/
String key = (String) iterator.next();
/**
* once we know the 'key', we can get the value from the HashMap
* by calling get() method
*/
String value = map.get(key);
System.out.println("Key: " + key + ", Value: " + value);
}
}
}
In onclick, after you decrement the value call notifyDataSetChanged()
notifyDataSetChanged
but its a costly operation, since it refreshes complete list
I am using an AsyncTask to parse a very large txt file in my application and i noticed something weird: The first time this AsyncTask is called it takes very long time to finish(10-20 seconds) and the next times it's almost instantly.
So i am guessing i should somehow load the txt file into memory when the app starts and go from there.
Is there any ways to do this or is this the right thing to do in the first place?
Should some kind of cache implementation solve my problem?
Would it be a good idea to use the Android Cache system?
This is my AsyncTask for referece:
public class AnalyzeReviewsAsync extends AsyncTask<ArrayList<Place.Review>, String, String> {
private final Activity activity;
private ProgressDialog progressDialog;
private SinglePlaceCallbacks callbacks;
public AnalyzeReviewsAsync(Activity activity, SinglePlaceCallbacks callbacks) {
this.activity = activity;
this.callbacks = callbacks;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(activity);
progressDialog.setMessage("Analyzing...");
progressDialog.show();
}
#Override
protected String doInBackground(ArrayList<Place.Review>... params) {
try {
return parseReviews(params[0]);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressDialog.dismiss();
String review = s == null ? "Not present" : s;
callbacks.setReviewsTxt(review);
}
private String parseReviews(ArrayList<Place.Review> reviewArrayList) throws IOException {
if(reviewArrayList!=null && reviewArrayList.size()>0) {
String reviewOutput = "";
for (Place.Review r : reviewArrayList) {
reviewOutput += "<p> <font color='" + getReviewColor(SentiWordNet.getInstance().analyzeReview(r.text)) + "'>";
reviewOutput += r.text;
reviewOutput += "</font></p>";
}
return reviewOutput;
}else{
return null;
}
}
private String getReviewColor(String review) {
if (review.equals("very positive")) {
//return Constants.getContext().getResources().getString(R.color.very_positive);
return "lime";
} else if (review.equals("positive")) {
//return Constants.getContext().getResources().getString(R.color.positive);
return "teal";
} else if (review.equals("negative")) {
//return Constants.getContext().getResources().getString(R.color.negative);
return "maroon";
} else if (review.equals("very negative")) {
//return Constants.getContext().getResources().getString(R.color.very_negative);
return "red";
} else {
//return Constants.getContext().getResources().getString(R.color.neutral);
return "grey";
}
}
}
Nothing fails the first time, so it is nothing different in code, here is my SentiWordNet class for referece:
public class SentiWordNet {
private Map<String, Double> dictionary;
private static SentiWordNet _instance = null;
private SentiWordNet(Context context) throws IOException {
// This is our main dictionary representation
dictionary = new HashMap<String, Double>();
// From String to list of doubles.
HashMap<String, HashMap<Integer, Double>> tempDictionary = new HashMap<String, HashMap<Integer, Double>>();
InputStream rawRes = context.getResources().openRawResource(R.raw.swn);
BufferedReader csv = null;
try {
csv = new BufferedReader(new InputStreamReader(rawRes, "UTF8"));
int lineNumber = 0;
String line;
while ((line = csv.readLine()) != null) {
lineNumber++;
// If it's a comment, skip this line.
if (!line.trim().startsWith("#")) {
// We use tab separation
String[] data = line.split("\t");
String wordTypeMarker = data[0];
// Example line:
// POS ID PosS NegS SynsetTerm#sensenumber Desc
// a 00009618 0.5 0.25 spartan#4 austere#3 ascetical#2
// ascetic#2 practicing great self-denial;...etc
// Is it a valid line? Otherwise, through exception.
if (data.length != 6) {
throw new IllegalArgumentException(
"Incorrect tabulation format in file, line: "
+ lineNumber
);
}
// Calculate synset score as score = PosS - NegS
Double synsetScore = Double.parseDouble(data[2])
- Double.parseDouble(data[3]);
// Get all Synset terms
String[] synTermsSplit = data[4].split(" ");
// Go through all terms of current synset.
for (String synTermSplit : synTermsSplit) {
// Get synterm and synterm rank
String[] synTermAndRank = synTermSplit.split("#");
String synTerm = synTermAndRank[0] + "#"
+ wordTypeMarker;
int synTermRank = Integer.parseInt(synTermAndRank[1]);
// What we get here is a map of the type:
// term -> {score of synset#1, score of synset#2...}
// Add map to term if it doesn't have one
if (!tempDictionary.containsKey(synTerm)) {
tempDictionary.put(synTerm,
new HashMap<Integer, Double>());
}
// Add synset link to synterm
tempDictionary.get(synTerm).put(synTermRank,
synsetScore);
}
}
}
// Go through all the terms.
for (Map.Entry<String, HashMap<Integer, Double>> entry : tempDictionary
.entrySet()) {
String word = entry.getKey();
Map<Integer, Double> synSetScoreMap = entry.getValue();
// Calculate weighted average. Weigh the synsets according to
// their rank.
// Score= 1/2*first + 1/3*second + 1/4*third ..... etc.
// Sum = 1/1 + 1/2 + 1/3 ...
double score = 0.0;
double sum = 0.0;
for (Map.Entry<Integer, Double> setScore : synSetScoreMap
.entrySet()) {
score += setScore.getValue() / (double) setScore.getKey();
sum += 1.0 / (double) setScore.getKey();
}
score /= sum;
dictionary.put(word, score);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (csv != null) {
csv.close();
}
}
}
public static SentiWordNet getInstance() throws IOException {
if (_instance == null) {
_instance = new SentiWordNet(Constants.getContext());
}
return _instance;
}
public Double extract(String word) {
Double total = (double) 0;
if (dictionary.get(word + "#n") != null) {
total = dictionary.get(word + "#n") + total;
}
if (dictionary.get(word + "#a") != null) {
total = dictionary.get(word + "#a") + total;
}
if (dictionary.get(word + "#r") != null) {
total = dictionary.get(word + "#r") + total;
}
if (dictionary.get(word + "#v") != null) {
total = dictionary.get(word + "#v") + total;
}
return total;
}
public String analyzeReview(String review) {
String[] words = review.split("\\s+");
double totalScore = 0, averageScore;
for (String word : words) {
word = word.replaceAll("([^a-zA-Z\\s])", "");
if (_instance.extract(word) == null) {
continue;
}
Log.d("Total Score", String.valueOf(totalScore));
totalScore += _instance.extract(word);
}
averageScore = totalScore;
if (averageScore >= 0.75) {
return "very positive";
} else if (averageScore > 0.25 && averageScore < 0.5) {
return "positive";
} else if (averageScore >= 0.5) {
return "positive";
} else if (averageScore < 0 && averageScore >= -0.25) {
return "negative";
} else if (averageScore < -0.25 && averageScore >= -0.5) {
return "negative";
} else if (averageScore <= -0.75) {
return "very negative";
}
return "neutral";
}
I have created a Custom listview and set data by parsing a link and sorted them inside the list. Now when I am going to make a click and get the value of the individual object of a row I can't get the object of clicked row.
public class MainActivity extends Activity implements OnChildClickListener,
OnItemClickListener {
private ExpandableListView mExpandableListView;
private List<GroupEntity> mGroupCollection;
String URL;
ArrayList<EventParsingClass> EventObject_Collection = new ArrayList<EventParsingClass>();
ArrayList<Date> DateArray = new ArrayList<Date>();
ArrayList<ArrayList<EventParsingClass>> arrayOfEventDescription = new ArrayList<ArrayList<EventParsingClass>>();
MyListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.event_mainactivity);
prepareResource();
initPage();
URL = "http://..............";
ParsingWithURL(URL);
}
private void ParsingWithURL(String uRL2) {
// TODO Auto-generated method stub
new JSONPARSINGFOREVENTSTREAM().execute(URL);
}
private class JSONPARSINGFOREVENTSTREAM extends
AsyncTask<String, Void, String> {
private final String TAG_ID = "id";
private final String TAG_Title = "title";
private final String TAG_Description = "description";
private final String TAG_StartDate = "start_datetime";
private final String TAG_EndDate = "end_datetime";
private final String TAG_City = "place_city";
private final String TAG_Club = "place_club";
private final String TAG_AgeLimit = "event_agelimit";
private static final String TAG_Event_streamable = "data";
EventParsingClass EPC;
JSONArray streamable = null;
ProgressDialog pDialog;
#SuppressLint("SimpleDateFormat")
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
Log.d("************PARAMS", arg0[0]);
JSONParser jparser = new JSONParser();
JSONObject json = jparser.getJSONFromUrl(arg0[0]);
try {
streamable = json.getJSONArray(TAG_Event_streamable);
for (int i = 0; i < streamable.length(); i++) {
EPC = new EventParsingClass();
JSONObject c = streamable.getJSONObject(i);
EPC.setId(c.getString(TAG_ID));
EPC.setPlace_city(c.getString(TAG_City));
EPC.setPlace_club(c.getString(TAG_Club));
EPC.setTitle(c.getString(TAG_Title));
EPC.setDescription(c.getString(TAG_Description));
EPC.setSratdate_time(c.getString(TAG_StartDate));
EPC.setEnddate_time(c.getString(TAG_EndDate));
EPC.setEvent_agelimit(c.getString(TAG_AgeLimit));
long difference = EPC.geEnddate_time_date().getTime()
- EPC.getSratdate_time_date().getTime();
int day_difference = (int) (difference / (1000 * 3600 * 24));
// Log.d("Difference", "" + day_difference);
if (day_difference == 0) {
AddDay(EPC.getSratdate_time_date());
} else {
if (DateArray.size() == 0) {
DateArray.add(EPC.getSratdate_time_date());
long startday = EPC.getSratdate_time_date()
.getTime();
for (int k = 1; k <= day_difference; k++) {
long constructedday = startday
+ (1000 * 3600 * 24) * k;
Date Constructed_value = new Date(
constructedday);
DateArray.add(Constructed_value);
}
} else {
AddDay(EPC.getSratdate_time_date());
long startday = EPC.getSratdate_time_date()
.getTime();
for (int k = 1; k <= day_difference; k++) {
long constructedday = startday
+ (1000 * 3600 * 24) * k;
Date Constructed_value = new Date(
constructedday);
AddDay(Constructed_value);
}
}
}
EventObject_Collection.add(EPC);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
private void AddDay(Date value) {
// TODO Auto-generated method stub
if (DateArray.size() == 0) {
DateArray.add(value);
} else {
boolean b = true;
for (Date s : DateArray) {
if (s.equals(value)) {
b = false;
break;
}
}
if (b) {
DateArray.add(value);
}
}
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.d("+++++++++++++++++++++++number of Items in List", ""
+ DateArray.size());
AddDetailedItemToListView();
AddHeaderItemsToListView();
pDialog.dismiss();
}
private void AddDetailedItemToListView() {
// TODO Auto-generated method stub
for (Date s : DateArray) {
ArrayList<EventParsingClass> constructed_arrayfor_items = new ArrayList<EventParsingClass>();
for (int g = 0; g < EventObject_Collection.size(); g++) {
EventParsingClass EVPC = EventObject_Collection.get(g);
long new_startdate = EVPC.getSratdate_time_date().getTime();
long new_endtdate = EVPC.geEnddate_time_date().getTime();
long date = s.getTime();
if (date >= new_startdate && date <= new_endtdate) {
Log.d("^^^^^^^^^^^ Value Of Date ", "" + s);
Log.d("^^^^^^^^^^^ Value Of StartDay ",
"" + EVPC.getSratdate_time_date());
Log.d("^^^^^^^^^^^ Value Of EndDay ",
"" + EVPC.geEnddate_time_date());
constructed_arrayfor_items.add(EVPC);
}
}
arrayOfEventDescription.add(constructed_arrayfor_items);
Log.d("^^^^^^^^^^^^^^^^^^^arrayOfEventDescription", ""
+ arrayOfEventDescription);
}
}
private void AddHeaderItemsToListView() {
// TODO Auto-generated method stub
ListView lv = (ListView) findViewById(R.id.list_evevnt);
LayoutInflater i = LayoutInflater.from(MainActivity.this);
List<Item> items = new ArrayList<Item>();
int length_of_datearray = DateArray.size();
Log.d("!!!!!!!!!!!!!!!", "" + DateArray.size());
Log.d("EEEEEEEEEEEEEEEEEEEE", "" + arrayOfEventDescription.size());
for (ArrayList<EventParsingClass> It : arrayOfEventDescription) {
Log.d("", "" + It.size());
for (EventParsingClass oETC : It) {
Log.d("*******" + oETC.getTitle(),
"" + oETC.getSratdate_time_date());
}
}
for (int m = 0; m < length_of_datearray; m++) {
String day_of_header = (String) android.text.format.DateFormat
.format("EEEE", DateArray.get(m));
String month_of_header = (String) android.text.format.DateFormat
.format("MMM", DateArray.get(m));
String date_of_header = (String) android.text.format.DateFormat
.format("dd", DateArray.get(m));
String total_header = day_of_header + " " + month_of_header
+ " " + date_of_header;
items.add(new Header(i, "" + total_header));
ArrayList<EventParsingClass> Arraylist_for_loop = arrayOfEventDescription
.get(m);
for (int h = 0; h < Arraylist_for_loop.size(); h++) {
String description = Arraylist_for_loop.get(h).getId();
String title = Arraylist_for_loop.get(h).getTitle();
String place_city = Arraylist_for_loop.get(h)
.getPlace_city();
String age_limit = Arraylist_for_loop.get(h)
.getEvent_agelimit();
String dayOfTheWeek = (String) android.text.format.DateFormat
.format("EEEE", Arraylist_for_loop.get(h)
.getSratdate_time_date());
String DayofWeek = dayOfTheWeek;
if (!(dayOfTheWeek == day_of_header)) {
DayofWeek = day_of_header;
}
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date d = new Date();
String Today = sdf.format(d);
String Value_of_today = "";
if (Today.contentEquals(DayofWeek)) {
Value_of_today = "Today";
}
items.add(new EventItem(i, Value_of_today, DayofWeek,
"12:00", title, description, place_city, "10",
age_limit));
}
}
MyListAdapter adapter = new MyListAdapter(MainActivity.this, items);
lv.setAdapter(adapter);
lv.setOnItemClickListener(MainActivity.this);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(true);
pDialog.show();
}
}
private void prepareResource() {
mGroupCollection = new ArrayList<GroupEntity>();
for (int i = 1; i < 3; i++) {
GroupEntity ge = new GroupEntity();
ge.Name = "City " + i;
for (int j = 1; j < 4; j++) {
GroupItemEntity gi = ge.new GroupItemEntity();
gi.Name = "Venu" + j;
ge.GroupItemCollection.add(gi);
}
mGroupCollection.add(ge);
}
}
private void initPage() {
mExpandableListView = (ExpandableListView) findViewById(R.id.expandableListView);
ExpandableListAdapter adapter = new ExpandableListAdapter(this,
mExpandableListView, mGroupCollection);
mExpandableListView.setAdapter(adapter);
mExpandableListView.setOnChildClickListener(this);
}
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
Toast.makeText(getApplicationContext(), childPosition + "Clicked",
Toast.LENGTH_LONG).show();
return true;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
EventParsingClass obj = (EventParsingClass) parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), obj.getPlace_city() + "Clicked",Toast.LENGTH_LONG).show();
}
}
How can I proceed in these two scenarios?
EventParsingClass EPSP= ??? and
EPSP.getid= ??
fetch[0]="XXX"
fetch[1]="YYY"
fetch[2]="ZZZ"
lv.setOnItemClickListener(MainActivity.this);
public void onItemClick(AdapterView<?> parent, View view, int position,long id)
Toast.makeText(getApplicationContext(), fetch[position] + "Clicked",
Toast.LENGTH_LONG).show();
}
just declare fetch[position] to get the value of clicked item. hope this will give you some solution.
Use int position to find out values from your data list (array list or what ever you used).
lv.setOnItemClickListener(MainActivity.this);
public void onItemClick(AdapterView<?> parent, View view, int position,long id)
Toast.makeText(getApplicationContext(), EPSP.getid(position) + "Clicked",Toast.LENGTH_LONG).show();
}
EventItem item = (EventItem) parent.getItemAtPosition(position);
Now you have a hold of EventItem. So you can start using the get methods of your EventItem class in order to get whatever you want from it.
I got the solution:
EventParsingClass new_method(int value) {
int item_count = 0;
for (int i = 0; i < arrayOfEventDescription.size(); i++) {
ArrayList<EventParsingClass> Arraylist_for_loop = arrayOfEventDescription
.get(i);
item_count++;
for (int j = 0; j < Arraylist_for_loop.size(); j++) {
if (value == item_count) {
return Arraylist_for_loop.get(j);
}
item_count++;
}
}
return null;
}
And call it from here:
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
EventParsingClass newObject = new_method(arg2);
if (newObject == null) {
} else {
Log.d("Generated Value Id : ", "" + newObject.getId());
Toast.makeText(getApplicationContext(),
"Item Clicked" + arg2 + "-----" + newObject.getTitle(),
Toast.LENGTH_LONG).show();
}
}
I am working with Section list view in Android to show Call details according to date.
Means under a particular date number of call details. But when I get 2 calls under the same date, the last date is visible only and the list does not show the rest of the calls of that date.
Calls under different dates are shown correctly but calls under same date are not shown correctly, only the last call is shown.
I am using the below code:
public String response = "{ \"Message\":\"Success\", "
+ "\"Data\":[ { \"ACCOUNT\":\"000014532497\", "
+ "\"DATE\":\"8/6/2006\", \"TIME\":\"15:37:14\", "
+ "\"CH_ITEM\":\"341T\", \"ITEM\":\"TIMEUSED\", "
+ "\"DESCRIPTION\":\"FROM3103475779\", \"DETAIL\":"
+ "\"UnitedKingdom011441980849463\", \"QUANTITY\":84, "
+ "\"RATE\":0.025, \"AMOUNT\":2.1, \"ACTUAL\":83.2, "
+ "\"NODE_NAME\":\"TNT02\", \"USER_NAME\":\"Shailesh Sharma\""
+ ", \"MODULE_NAME\":\"DEBIT\", \"ANI\":\"3103475779\", "
+ "\"DNIS\":\"3103210104\", \"ACCOUNT_GROUP\":\"WEBCC\", "
+ "\"SALES_REP\":\"sascha_d\", \"SALES_REP2\":\"\", \"SALES_REP3"
+ "\":\"\", \"IN_PORT\":\"I10\", \"EXTRA1\":\"RATE\", \"EXTRA2\":"
+ "\"44\", \"EXTRA3\":\"UnitedKingdom\", \"OUT_PORT\":\"I70\", "
+ "\"CRN\":\"WEBCC\", \"CallId\":null, \"ID\":4517734, \"PhoneNumber"
+ "\":\"011441980849463\" }, {\"ACCOUNT\":\"000014532497\",\"DATE\":"
+ "\"8/6/2006\",\"TIME\":\"09:22:57\",\"CH_ITEM\":\"541T\",\"ITEM\":"
+ "\"TIMEUSED\",\"DESCRIPTION\":\"FROM3103475779\",\"DETAIL\":"
+ "\"UnitedKingdom011447914422787\",\"QUANTITY\":1,\"RATE\":0.29,"
+ "\"AMOUNT\":0.29,\"ACTUAL\":0.5,\"NODE_NAME\":\"TNT02\",\"USER_NAME"
+ "\":\"Tusshar\",\"MODULE_NAME\":\"DEBIT\",\"ANI\":\"3103475779\",\"DNIS"
+ "\":\"6173950047\",\"ACCOUNT_GROUP\":\"WEBCC\",\"SALES_REP\":\"sascha_d"
+ "\",\"SALES_REP2\":\"\",\"SALES_REP3\":\"\",\"IN_PORT\":\"I30\",\"EXTRA1"
+ "\":\"RATE\",\"EXTRA2\":\"44\",\"EXTRA3\":\"UnitedKingdom-Special\","
+ "\"OUT_PORT\":\"I90\",\"CRN\":\"WEBCC\",\"CallId\":null,\"ID\":4535675,"
+ "\"PhoneNumber\":\"011447914422787\"}, ], \"NumberOfContacts\":2, "
+ "\"TotalCharges\":4.830000000000001 }";
try {
JSONObject jsonObj = new JSONObject(response);
String message = jsonObj.getString("Message");
if (message != null && message.equalsIgnoreCase("Success")) {
JSONArray dataArray = jsonObj.getJSONArray("Data");
System.out.println(dataArray.length());
for (int i = 0; i < dataArray.length(); i++) {
JSONObject history = dataArray.getJSONObject(i);
_date = history.getString("DATE");
String updatedDate = createDateFormat(_date);
// notes =new ArrayList<String>();
itemList = new ArrayList<Object>();
// ADDING DATE IN THE ARRAYLIST<String>
days.add(updatedDate);
_username = history.getString("USER_NAME");
_number = history.getString("PhoneNumber");
_time = history.getString("TIME");
_amount = history.getString("AMOUNT");
_duration = history.getString("QUANTITY");
/*
* notes.add(_username); notes.add(_number);
* notes.add(_time);
*/
AddObjectToList(_username, _number, _time, _amount,
_duration);
// listadapter = new <String>(this, R.layout.list_item,
// notes);
listadapter = new ListViewCustomAdapter(this, itemList);
adapter.addSection(days.get(i), listadapter);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public class SeparatedListAdapter extends BaseAdapter {
/*
* public final Map<String, Adapter> sections = new
* LinkedHashMap<String, Adapter>();
*/
public final Map<String, Adapter> sections = new LinkedHashMap<String, Adapter>();
public final ArrayAdapter<String> headers;
public final static int TYPE_SECTION_HEADER = 0;
public SeparatedListAdapter(Context context) {
headers = new ArrayAdapter<String>(context, R.layout.list_header);
}
public void addSection(String section, Adapter adapter) {
this.headers.add(section);
this.sections.put(section, adapter);
}
public Object getItem(int position) {
for (Object section : this.sections.keySet()) {
Adapter adapter = sections.get(section);
int size = adapter.getCount() + 1;
// check if position inside this section
if (position == 0)
return section;
if (position < size)
return adapter.getItem(position - 1);
// otherwise jump into next section
position -= size;
}
return null;
}
public int getCount() {
// total together all sections, plus one for each section header
int total = 0;
for (Adapter adapter : this.sections.values())
total += adapter.getCount() + 1;
return total;
}
#Override
public int getViewTypeCount() {
// assume that headers count as one, then total all sections
int total = 1;
for (Adapter adapter : this.sections.values())
total += adapter.getViewTypeCount();
return total;
}
#Override
public int getItemViewType(int position) {
int type = 1;
for (Object section : this.sections.keySet()) {
Adapter adapter = sections.get(section);
int size = adapter.getCount() + 1;
// check if position inside this section
if (position == 0)
return TYPE_SECTION_HEADER;
if (position < size)
return type + adapter.getItemViewType(position - 1);
// otherwise jump into next section
position -= size;
type += adapter.getViewTypeCount();
}
return -1;
}
public boolean areAllItemsSelectable() {
return false;
}
#Override
public boolean isEnabled(int position) {
return (getItemViewType(position) != TYPE_SECTION_HEADER);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
int sectionnum = 0;
for (Object section : this.sections.keySet()) {
Adapter adapter = sections.get(section);
int size = adapter.getCount() + 1;
// check if position inside this section
if (position == 0)
return headers.getView(sectionnum, convertView, parent);
if (position < size)
return adapter.getView(position - 1, convertView, parent);
// otherwise jump into next section
position -= size;
sectionnum++;
}
return null;
}
#Override
public long getItemId(int position) {
return position;
}
}
This is my actual requirement:
This is what is happening right now.
SectionListExampleActivity is my Main class in which I am getting RESPONSE from JSON web service. In getJSONResposne method I am calling the EntryAdaptor.
There are two separate geter setter classes for SECTION HEADER and ITEM ENTRY for each header.
public class SectionListExampleActivity extends Activity implements OnClickListener, OnItemSelectedListener, IServerResponse {
/** Called when the activity is first created. */
private ArrayList<Item> items = new ArrayList<Item>();
boolean firstTime = true;
private Spinner _spinner=null;
private ArrayAdapter _amountAdaptor = null;
private ArrayList<String> _monthList =new ArrayList<String>();
private ListView _list=null;
private Button _monthButton=null;
private ImageButton _backImageButton=null;
private ImageButton _headerImageButton=null;
private String _token;
private String _account;
private Point p=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.account_history);
String response = this.getIntent().getExtras().getString("history_resp");
_token = Constant.AUTH_TOKEN;
_account = Constant.ACCOUNT_NUM;
_list = (ListView)findViewById(R.id.listview);
getJSON_Response(response,Constant.PID_ACCOUNT_HISTORY);
EntryAdapter adapter = new EntryAdapter(this, items);
_list.setAdapter(adapter);
_monthList.add("Months");
_monthList.add("January");
_monthList.add("February");
_monthList.add("March");
_monthList.add("April");
_monthList.add("May");
_monthList.add("June");
_monthList.add("July");
_monthList.add("August");
_monthList.add("September");
_monthList.add("October");
_monthList.add("November");
_monthList.add("December");
_spinner = (Spinner)findViewById(R.id.month_spinner);
_amountAdaptor = new ArrayAdapter(this,
android.R.layout.simple_spinner_dropdown_item,
_monthList);
_spinner.setAdapter(_amountAdaptor);
_spinner.setOnItemSelectedListener(this);
_monthButton = (Button)findViewById(R.id.monthSpinner_button);
_monthButton.setOnClickListener(this);
_backImageButton = (ImageButton)findViewById(R.id.back_ImageButton);
_backImageButton.setOnClickListener(this);
_headerImageButton =(ImageButton)findViewById(R.id.header_ImageButton);
_headerImageButton.setOnClickListener(this);
}
private void getJSON_Response(String response,int pid) {
switch (pid) {
case Constant.PID_ACCOUNT_HISTORY:
try {
JSONObject jsonObj = new JSONObject(response);
String message = jsonObj.getString("Message");
if(message!=null && message.equalsIgnoreCase("Success")){
JSONArray dataArray = jsonObj.getJSONArray("Data");
System.out.println(dataArray.length());
String lastAddedDate = null;
for (int i = 0; i <dataArray.length(); i++) {
JSONObject history = dataArray.getJSONObject(i);
String date = history.getString("DATE");
if(firstTime || !(date.equalsIgnoreCase(lastAddedDate))){
firstTime=false;
lastAddedDate = date;
items.add(new SectionItem(date));
}
String username= history.getString("USER_NAME");
String number = history.getString("PhoneNumber");
String time = history.getString("TIME");
String amount=history.getString("AMOUNT");
String duration =history.getString("QUANTITY");
items.add(new EntryItem(username,duration,amount,number,time));
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
default:
break;
}
}
#Override
public void onClick(View v) {
if(v==_monthButton){
_spinner.performClick();
}else if(v==_backImageButton){
SectionListExampleActivity.this.finish();
}else if(v== _headerImageButton){
if (p != null)
showPopup(SectionListExampleActivity.this, p);
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position,
long arg3) {
if(position!=0){
switch (parent.getId()) {
case R.id.month_spinner:
String selectedItem = _spinner.getSelectedItem().toString();
_monthButton.setBackgroundResource(R.drawable.month_blank);
_monthButton.setText(selectedItem);
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
String _historyURL = Constant.prodORdevUrl + "GetAccountHistory?token="+_token+"&account="+_account+"&month="+month+"&year="+year;
getHistory(_historyURL,true);
break;
default:
break;
}
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
public class EntryAdapter extends ArrayAdapter<Item> implements IServerResponse {
private Context context;
private ArrayList<Item> items;
private LayoutInflater vi;
private String _token;
private String _account;
public EntryAdapter(Context context,ArrayList<Item> items) {
super(context,0, items);
this.context = context;
this.items = items;
vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
_token = Constant.AUTH_TOKEN;
_account = Constant.ACCOUNT_NUM;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
final Item i = items.get(position);
if (i != null) {
if(i.isSection()){
SectionItem si = (SectionItem)i;
v = vi.inflate(R.layout.list_item_section, null);
v.setOnClickListener(null);
v.setOnLongClickListener(null);
v.setLongClickable(false);
final TextView sectionView = (TextView) v.findViewById(R.id.list_item_section_text);
String date =createDateFormat(si.getTitle());
sectionView.setText(date);
}else{
EntryItem ei = (EntryItem)i;
v = vi.inflate(R.layout.list_item_entry, null);
final RelativeLayout relay = (RelativeLayout)v.findViewById(R.id.account_history_item_relay);
final TextView username = (TextView)v.findViewById(R.id.user_name_textview);
final TextView amount = (TextView)v.findViewById(R.id.amount_textview);
final TextView duration = (TextView)v.findViewById(R.id.duration_textview);
final TextView phone = (TextView)v.findViewById(R.id.phone_no_textview);
final TextView time = (TextView)v.findViewById(R.id.time_textview);
relay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
makeCall(phone.getText().toString());
}
});
if (username != null)
username.setText(ei.username);
if(amount != null)
amount.setText(ei.duration + "min");
if(duration != null)
duration.setText("$"+ ei.amount);
if(phone != null)
phone.setText(ei.number);
if(time != null)
time.setText(ei.time);
}
}
return v;
}
void makeCall(String destination) {
if(_token!=null && _account!=null){
if(destination!=null && !destination.equals("")){
String phoneNumber = Constant.getPhoneNumber(this.context.getApplicationContext());
if(phoneNumber!=null && phoneNumber.length()>0){
String callURL =WebService.WEB_SERVICE_URL+"PlaceLongDistanceCall?token="+_token +
"&phonenumber="+phoneNumber+"&destinationNumber="+destination+"&authtoken="+_token;
getCall(callURL,true);
}else{
Constant.showToast(this.context, Constant.INSERT_SIM);
}
}else{
Constant.showToast(this.context, "In valid destination number.");
}
}
}
}