I have some problem in updating the values to hash-table,here is my problem i will explain it clearly.
1.I have getting the response from server,i am adding the values to layout,by using layout Layout-Inflater.
2.in our application we have streaming request.when the streaming request is turned on the values need to be updated regularly.
storing values in hash-tables
Hashtable<String, View> indicesHashtable = new Hashtable<String, View>();
For(Step 1)code i have written belowthe code.
private void addIndices(LinearLayout parent, final String key,final String value) {
LayoutInflater factory = LayoutInflater.from(mContext);
final View row = factory.inflate(R.layout.indices_values, null);
final TextView keyTextView = (TextView) row.findViewById(R.id.txtCompany);
final TextView valueTextView = (TextView) row.findViewById(R.id.txtIndex);
final Button iconImageView = (Button) row.findViewById(R.id.btnIcon);
row.setBackgroundResource(android.R.drawable.list_selector_background);
if (value.length() > 0) {
keyTextView.setText(Html.fromHtml("<b>"+indices.get(key)+"</b>"));
valueTextView.setText(Html.fromHtml(value));
if(quoteArrowIconId != -1)
iconImageView.setBackgroundResource(quoteArrowIconId);
else
iconImageView.setBackgroundDrawable(null);
}else{
keyTextView.setText(Html.fromHtml(key));
}
indicesHashtable.put(key, row);
parent.addView(row);
}
For(Step 2)i need help from you guys.
i have written code..that i have shown below.
private void handleResponseOfResponses(ResponseParser response) {
Hashtable responses = (Hashtable) response.getValue(Response_890.RESPONSES);
String[] symbols = new String[responses.size()];
int index = 0;
indicesHashtable.clear();
for(int i =indicesSymbols.length-1; i >= 0; i--){
Enumeration e = responses.keys();
while (e.hasMoreElements()) {
ResponseParser subResponse = (ResponseParser) responses.get(e.nextElement());
if (subResponse.getResponseCode() == ResponseCodes.QUOTES_RESPONSE) {
String[] quoteProperties = (String[]) subResponse.getValue(Response_312.QUOTES_KEY);
if(quoteProperties[0].equalsIgnoreCase(indicesSymbols[i])){
// symbolTable.put(quoteProperties[0].toUpperCase(), index);
symbols[index++] = quoteProperties[0];
String value = quoteValue(quoteProperties);
For displaying the values coming for response i have added (AddIndices)method
addIndices(linear_Indices, quoteProperties[0], value);
}
}
}
}
autoscroll();
indicesStreamerClient = new StreamerClient(indicesSymbols){
#Override
public void onStreamDataReceived(QuoteData quoteData) {
System.out.println("onStreamDataReceived () -> "+quoteData.getSymbol());
HERE I NEED TO ADDED ANOTHER METHOD FOR UPDATING THE VALUES..HOW I CAN WRITE THE CODE.
};
};
Streamer.getInstance(mContext).registerStramerClient(indicesStreamerClient);
}
Guys i am fresher as well as new to andriod.
Thanks in advance!!!!!!
Related
I'm developing a recipe book and I'm implementing this method to insert my Recipe in the Database. In the for cycle I get the ingredient's name and quantity from multiples EditText, saving each of them in an Ingredient.class instance (newIngredient). Then I insert the instance into the DB and add it to an ArrayList. The followings "if conditions" are for the title, time and other Recipe's attributes. Finally, I also insert Recipe and Tag instances in the relatives DB's tables and I close DB.
public void saveRecipe() {
dbHelper = new DatabaseHelper(context);
// creating new recipe from user input
Ingredient newIngredient;
String title, childIngredient, instruction, tag;
int target, time, childQuantity, calories;
int countIngredients = parentIngredientLayout.getChildCount();
int countTags = chipGroup.getChildCount();
ArrayList<Ingredient> ingredients = null;
ArrayList<Tag> tags = null;
View childViewIng = null;
EditText childTextViewI = null;
EditText childTextViewQ = null;
// ingredients fields settings
for (int d=0; d<countIngredients; d++) {
childViewIng = parentIngredientLayout.getChildAt(d);
childTextViewI = childViewIng.findViewById(R.id.ingredientsField);
childTextViewQ = childViewIng.findViewById(R.id.quantityField);
childIngredient = childTextViewI.getText().toString();
childQuantity = Integer.parseInt(childTextViewQ.getText().toString());
newIngredient = new Ingredient(childIngredient, childQuantity);
dbHelper.insertIngredient(newIngredient);
ingredients.add(newIngredient);
}
//recipe fields settings
if (photoPath1 == null)
photoPath1 = "";
if (photoPath2 == null)
photoPath2 = "";
if (photoPath3 == null)
photoPath3 = "";
if (titleText.getText().toString().isEmpty()) {
title = "";
} else {
title = titleText.getText().toString();
}
if (targetNumber.getText().toString().isEmpty()) {
target = 0;
} else {
target = Integer.parseInt(targetNumber.getText().toString());
}
if (timeNumber.getText().toString().isEmpty()) {
time = 0;
} else {
time = Integer.parseInt(timeNumber.getText().toString());
}
if (instructionText.getText().toString().isEmpty()) {
instruction = "";
} else {
instruction = instructionText.getText().toString();
}
if (caloriesNumber.getText().toString().isEmpty()) {
calories = 0;
} else {
calories = Integer.parseInt(caloriesNumber.getText().toString());
}
if (tagName.getText().toString().isEmpty()) {
tag = "";
} else {
tag = tagName.getText().toString();
}
Recipe newRecipe = new Recipe(title, photoPath1, photoPath2, photoPath3, instruction, target, time, calories, ingredients);
Tag newTag = new Tag(tag);
dbHelper.insertRecipe(newRecipe);
dbHelper.insertTag(newTag);
dbHelper.close(); }
I found out by debugging that in this case is inserted only the first ingredient. I tried to move the FOR until the end of code, but in that case, are inserted both recipe and tag and always only the first ingredient. I think the problem is relative to the opening/closing of the DB. Can somebody help me?
Ingredient constructor:
public Ingredient(String ingredient_name, int quantity) {
this.ingredient_name = ingredient_name;
this.quantity = quantity;
}
dbHelper.insertIngredient(newIngredient) method:
public boolean insertIngredient(Ingredient ingredient) {
db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(INGREDIENT_NAME, ingredient.getIngredient_name());
contentValues.put(QUANTITY, ingredient.getQuantity());
contentValues.put(KEY_CREATED_AT, time.getTime().toString());
long result = db.insert(TBL_INGREDIENTS, null, contentValues);
//db.close();
Log.e(TAG, "Ingredient inserted!");
if (result == -1) {
return false;
} else {
return true;
}
}
Ok, thanks to your comment we got the problem :)
You are calling .add(newIngredient) on a list that you initialized with ArrayList<Ingredient> ingredients = null;
Change it to
ArrayList<Ingredient> ingredients = new ArrayList<Ingredient>();
and it will work :)
Good luck!
I built a fragment which use data in a web service call to display gridView list. It has about .5 second of delay to actually grab data and display the gridView on xml. Issue is that Everytime I come back from other pages or reorient the view, the delay happens. I don't know what I am missing but should the system save the last view in memory to display before it gets the real data from web service whenever I come back from other pages?
public class fragment_grid_room extends Fragment{
private static final String TAG = fragment_grid_room.class.getName();
public fragment_grid_room() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add this line in order for this fragment to handle menu events.
setRetainInstance(true);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//start async task to display rooms
DisplayGridRooms gridRooms = new DisplayGridRooms();
gridRooms.execute(new String[] { "params" });
View rootView = inflater.inflate(R.layout.fragment_roomgrid, container, false);
//rootView.findViewById(R.id.loadingPanel).setVisibility(View.VISIBLE);
//add current date
TextView dayTV = (TextView) rootView.findViewById(R.id.currentDate);
SimpleDateFormat sdf = new SimpleDateFormat("EEE, MMM d, yyyy");
Date now = new Date();
String strDate = sdf.format(now);
Log.d(TAG, "*****strdate"+strDate);
dayTV.setText(strDate);
return rootView;
}
//async task to display rooms
private class DisplayGridRooms extends AsyncTask<String, Void, JSONArray> {
JSONArray jsonArrayRooms;
#Override
protected JSONArray doInBackground(String... url) {
String email = getResources().getString(R.string.temp_login);
String pwd = getResources().getString(R.string.temp_pwd);
String username = "apark#anexinet.com";
webServiceRoom wsRoom = new webServiceRoom();
jsonArrayRooms = wsRoom.getRoomList(email, pwd, username);
//System.out.println("222******returning jsonroom with: "+jsonRoom.length());
return jsonArrayRooms;
}
#Override
protected void onPostExecute(JSONArray jsonArrayRooms) {
ArrayList<roomGrid> room_list = new ArrayList<roomGrid>();
int totalNumRooms=jsonArrayRooms.length();
int availNum=0;
for (int i = 0; i < jsonArrayRooms.length(); i++) {
roomGrid roomObject = new roomGrid();
try {
JSONObject jsonRoom = jsonArrayRooms.getJSONObject(i);
String[] temp = jsonRoom.getString("roomName").split("-");
String[] temp2 = temp[1].split("\\(");
roomObject.setRoomName(temp2[0].trim());
String roomStat = jsonRoom.getString("statusText");
roomObject.setStatus(roomStat);
room_list.add(roomObject);
if(roomStat.toLowerCase().contains("available")){ //count available rooms
availNum+=1;
};
} catch (Exception ex) {
Log.e(TAG, "json array exception for rooms:" + ex);
}
}
final GridView gridView = (GridView) getActivity().findViewById(R.id.gridview_room);
//set availability bar
TextView avalBar = (TextView) getActivity().findViewById(R.id.availableBar);
String availbilityText = "Available "+availNum+" of "+totalNumRooms;
avalBar.setText(availbilityText);
Window window = getActivity().getWindow();
View v = window.getDecorView();
ImageButton imageGrid = (ImageButton) v.findViewById(R.id.gridButton);
imageGrid.setVisibility(View.GONE);
Display display = getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
int numColFinal = 1;
if (width > 350) {
double numCol = width / 350;
numColFinal = (int) numCol;
}
gridView.setNumColumns(numColFinal);
Log.d(TAG, "screen width, numColFinal=" + width + "," + numColFinal);
// getActivity().findViewById(R.id.loadingPanel).setVisibility(View.GONE);
gridView.setAdapter(new CustomAdaptorRoomGrid(getActivity(), room_list));
//when list is clicked, move to detail page
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Object o = gridView.getItemAtPosition(position);
roomGrid fullObject = (roomGrid)o;
String roomName = fullObject.getRoomName();
Intent intent = new Intent(getActivity(), RoomTimeslotActivity.class)
.putExtra(Intent.EXTRA_TEXT, roomName);
startActivity(intent);
}
});
}
}
}
One way to fix the issue is by storing data in shared preferences every time you close your fragment.
First a little improvement. You can move the code below from onPostExecute() in doInBackground(). And then rather return JSONArray in onPostExecute() you can return your list of roomGrid
List<roomGrid> room_list = new ArrayList<roomGrid>();
int totalNumRooms=jsonArrayRooms.length();
int availNum=0;
for (int i = 0; i < jsonArrayRooms.length(); i++) {
roomGrid roomObject = new roomGrid();
try {
JSONObject jsonRoom = jsonArrayRooms.getJSONObject(i);
String[] temp = jsonRoom.getString("roomName").split("-");
String[] temp2 = temp[1].split("\\(");
roomObject.setRoomName(temp2[0].trim());
String roomStat = jsonRoom.getString("statusText");
roomObject.setStatus(roomStat);
room_list.add(roomObject);
if(roomStat.toLowerCase().contains("available")){
//count available rooms
availNum+=1;
};
}
catch (Exception ex) {
Log.e(TAG, "json array exception for rooms:" + ex);
}
}
In your class RoomGrid (the one you add in your list), add
method toJson() - which creates a JSONObjectinstance representing your data
static method public static RoomGrid from(JSONObject json) - which will create and return an RoomGrid instance (or null if json is null, empty, etc)
In you CustomAdaptorRoomGrid add
- getItems() which will return the list of RoomGrid you supplied when creating the adapter
in your fragment onDestroyView() add:
CustomAdaptorRoomGrid adapter = (CustomAdaptorRoomGrid) gridView.getAdapter();
int length = adapter != null && adapter.getItems() != null ? adapter.getItems().size() : 0;
if (length > 0) {
// create a JSONArray from the list
JSONArray array = new JSONArray();
for (RoomGrid item : adapter.getItems()) {
array.put(item.toJson();
}
// add the value in preferences
SharedPreferences prefs = ...;
prefs.edit().put("YOUR_KEY", array.toString()).apply();
}
And finally in your fragment onViewCreated() check for the array from the shared preferences and revert it to a list of your items and supply them to the adapter.
Then engage your task to download and refresh whatever you need.
I want to the change the text of the button which was clicked in a getView function. The text is changed but when the view is scrolled the text of other buttons which the same id is also changed. I don't want that. I want only the text of the button which was clicked to be changed.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final int i=position;
List dialog = DialogList.get(i);
final Object memid = dialog.get(2).toString();
final String dialogid = dialog.get(3).toString();
final String dialogtype = dialog.get(4).toString();
ImageView imageViews;
if (convertView == null) {
LayoutInflater layoutInflator = LayoutInflater.from(getContext());
convertView = layoutInflator.inflate(R.layout.invite_friends_list, null);
holder = new ViewHolder();
holder.friendsname = (TextView) convertView.findViewById(R.id.friendsname);
holder.profimage = (ImageView) convertView.findViewById(R.id.member_image);
holder.assign = (Button) convertView.findViewById(R.id.btnInvite);
convertView.setTag(holder);
}
holder = (ViewHolder) convertView.getTag();
holder.friendsname.setText(user_name);
holder.assign.setTag(holder);
holder.assign.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("assigntext", holder.assign.getText().toString());
SharedPreferences prfs = _context.getSharedPreferences("MyPref",
Context.MODE_PRIVATE);
String token = prfs.getString("apptoken", "");
String url = null;
if(dialogtype.equals("V"))
{
url = "http://www.jjhjjkh.com/index.php?/alkjlkjlk/dialog/invjlkjlkjklialogmember?apptoken="
+ token + "&dialogid=" + dialogid+"&mid="+memid.toString();
}
if(dialogtype.equals("P"))
{
url = "http://www.ckjhuihiuhiu.com/index.php?/kjij/dialog/inviuhuihuihuimember?apptoken="
+ token + "&dialogid=" + dialogid+"&mid="+memid.toString();
}
List<String> urlList = new ArrayList<String>();
Log.d("cat",url.toString());
// JSON Node names
String TAG_DETAILS = "invitemembers";
String TAG_MSG = "msg";
// contacts JSONArray
JSONArray dialogpublish = null;
JSONArray dialogs = null;
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
// Log.d("cat",json.toString());
try {
dialogpublish = json.getJSONArray(TAG_DETAILS);
// Log.d("apptoken",login.toString());
for (int i = 0; i < dialogpublish.length(); i++) {
JSONObject d = dialogpublish.getJSONObject(i);
String msg = d.getString(TAG_MSG);
//dialogs = d.getJSONArray("updatedialog");
if (msg.equals("success")) {
// ViewHolder mH = (ViewHolder)view.getTag();
//Integer currentPos = view.getTag();
String mem_id= view.getTag().toString();
if(mem_id.equals(memid))
{
Toast.makeText(_context, "Member invited Succesfully",Toast.LENGTH_LONG).show();
ViewHolder mH = (ViewHolder)view.getTag();
mH.assign.setText("Invited");
}
//view.setText("Invited");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I guess that is happenning because you are using the viewholder pattern. The viewholder pattern tends to cache views for performance optimization. try to write the adapter without using viewholder. If the list view items arent large in numbers.
Create a new HashMap in Adapter :
private HashMap<Integer, String> buttonTitleMap=new HashMap<Integer, String>();
Create a function getButtonTitle as below in Adapter :
private String getButtonTitle(int position){
if(buttonTitleMap.containsKey(position)){
return buttonTitleMap.get(position);
}else{
return "Your Normal Button text";
}
}
Then in getView() of Adapter, befor returning convertView, call :
....
holder.assign.setText(getButtonTitle(position));
holder.friendsname.setTag(position);
return convertView;
}
When the Button is clicked, you can get the list item position of the button. So what you need to do is to change the button title as you do before and also update the hashmap with the same value :
holder.assign.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
....
mH.assign.setText("Invited");
int position = (int)mH.friendsname.getTag();
buttonTitleMap.put(position,"Invited");
....
}
}
You are done.
Try
String mem_id= view.getTag().toString();
if(mem_id.equals(memid))
{
Toast.makeText(_context, "Member invited Succesfully",Toast.LENGTH_LONG).show();
((Button)view).setText("Invited");
}
I have a ListView that utilizes a CheckedTextView and a clear all button that has the following code:
btnClearAll.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int listsize = songsList.size();
filelv = (ListView)getView().findViewById(R.id.FileList);
checkedCount = 0;
for (int i=0; i<listsize-1; i++) {
// if(currentPlayList.get(i).equals ("Checked")){
songsList.get(i).get("songCheckedStatus").equals("Not Checked");
filelv.setItemChecked(i, false);
}
}
});
When the code executes, each array "songsList" value is set to "Not Checked" correctly, so I know that the button is working. However, the CheckedTextView items are not "unticking".
Where am I going wrong?
olution:
As mentioned above, I just set up a global variable and passed whether I wanted to Select All or Clear All to it. Then I just called my function for populating the ListView. As the ListView is built, it checks the variable in a simple "if" statement, and adds whether to check or uncheck. The cursor adapter then does the check/uncheck as it reruns.
//The code for clearing all.
btnClearAll.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
checkedCount = 0;
GetMusicMode = "ClearAll";
GetMusic getMusic = new GetMusic();
getMusic.execute();
}
});
And this from my data grabber for the ListView.
....
String track_Title = null;
String track_Path = null;
String track_Artist = null;
String track_Album = null;
String track_ID = null;
String track_TrackNumber = null;
String track_AlbumID = null;
String track_ArtistID = null;
String track_Checked = null;
if (Constants.GetMusicMode.equals("SelectAll")){
track_Checked = "Checked";
}else{
track_Checked = "Not Checked";
}
.....
.....
HashMap<String, String> song = new HashMap<String, String>();
song.put("songTitle", track_Title);
song.put("songPath", track_Path);
song.put("songArtist", track_Artist);
song.put("songAlbum", track_Album);
song.put("songTrackNumber", track_TrackNumber);
song.put("songID", track_ID);
song.put("songAlbumID", track_AlbumID);
song.put("songArtistID", track_ArtistID);
song.put("songCheckedStatus", track_Checked);
// Adding each song to SongList
songsList.add(song);
....throw to cursor adapter
and finally, this section from the cursoradapter getview
if (songsList.get(position).get("songCheckedStatus").equals("Checked")){
holder.checkTextView.setChecked(true);
}else{
holder.checkTextView.setChecked(false);
}
Hi can some one suggest me a sample example of how i can sort the textviews based on the numbers in textviews. I am able to get the text from the TextViews need to sort and place the lowest number first.
Thank you.
public void sortNumbers(View v) {
String[] numbers = new String[7];
numbers[0] = textView23.getText().toString();
numbers[1] = textView33.getText().toString();
numbers[2] = textView43.getText().toString();
numbers[3] = textView53.getText().toString();
numbers[4] = textView63.getText().toString();
numbers[5] = textView73.getText().toString();
numbers[6] = textView83.getText().toString();
Integer[] intValues = new Integer[numbers.length];
for (int i = 0; i < numbers.length; i++) {
intValues[i] = Integer.parseInt(numbers[i].trim());
}
Collections.sort(Arrays.asList(intValues));
for (int i = 0; i < intValues.length; i++) {
Integer intValue = intValues[i];
//here I want to assign sorted numberes to the TextViews
}
}
So I have followed Jeffrey's advice. Here is the code which still doesn't work properly. What could be wrong?
Created an array of TextViews:
TextView[] tvs = new TextView[7];
tvs[0] = textView23;
tvs[1] = textView33;
tvs[2] = textView43;
tvs[3] = textView53;
tvs[4] = textView63;
tvs[5] = textView73;
tvs[6] = textView83;
Sorted the array and assinged new values to the TextViews:
Arrays.sort(tvs, new TVTextComparator());
textView23.setText(tvs[0].getText().toString());
textView33.setText(tvs[1].getText().toString());
textView43.setText(tvs[2].getText().toString());
textView53.setText(tvs[3].getText().toString());
textView63.setText(tvs[4].getText().toString());
textView73.setText(tvs[5].getText().toString());
textView83.setText(tvs[6].getText().toString());
And here is the Comporator class:
public class TVTextComparator implements Comparator<TextView> {
public int compare(TextView lhs, TextView rhs) {
Integer oneInt = Integer.parseInt(lhs.getText().toString());
Integer twoInt = Integer.parseInt(rhs.getText().toString());
return oneInt.compareTo(twoInt);
}
}
to sort your textViews, first put them in an array,
TextView[] tvs = new TextView[7];
tvs[0] = textView23;
tvs[1] = textView33;
// and so on
note that if you have handle to the parent container, you could easily build the array by using ViewGroup.getChildCount() and getChildAt().
now write a comparator for a text view,
class TVTextComparator implements Comparator<TextView> {
#Override
public int compare(TextView lhs, TextView rhs) {
return lhs.getText().toString().compareTo(rhs.getText().toString());
// should check for nulls here, this is NOT a robust impl of compare()
}
}
now use the comparator to sort the array,
Arrays.sort(tvs, 0, tvs.length, new TVTextComparator());
public void sortNumbers(View v) {
String[] numbers = new String[7];
numbers[0] = textView23.getText().toString();
numbers[1] = textView33.getText().toString();
numbers[2] = textView43.getText().toString();
numbers[3] = textView53.getText().toString();
numbers[4] = textView63.getText().toString();
numbers[5] = textView73.getText().toString();
numbers[6] = textView83.getText().toString();
Integer[] intValues = new Integer[numbers.length];
for (int i = 0; i < numbers.length; i++) {
intValues[i] = Integer.parseInt(numbers[i].trim());
}
Collections.sort(Arrays.asList(intValues));
textView23.setText(intValues[0]);
textView33.setText(intValues[1]);
textView43.setText(intValues[2]);
textView53.setText(intValues[3]);
textView63.setText(intValues[4]);
textView73.setText(intValues[5]);
textView83.setText(intValues[6]);
}