Android Volley request weird “1 second” delay between multiple fast clicks - Android Q&A, Help & Troubleshooting

Sorry for my bad english, but i have problem and can't figure it out..
I have custom listview in my fragment for getting products from JSON array. And I have 3 ImageButtons in every listview row;
Plus Button(+), Minus Button(-) and Remove Button(X)..
So when i click each button, its calling JSON request for update product's piece number, getting new datas from response and repopulate array list.
Everything ok but, when I click that buttons faster, it seems there is 1 sec delay between multiple requests even first volley request has already done before.
Here is my JSON method in TableAdapter.java
Code:
[SIZE="3"]public void JSON(final int position, final int process) {
if (inProgress==false) {
dialog = new ProgressDialog(myContext);
dialog.setMessage("Updating.....");
dialog.show();
inProgress = true;
System.out.println("**** Now request is beginning............");
final int rowID = tableModelList.get(position).getID();
final int treeID = tableModelList.get(position).getAna_dal();
final float price = tableModelList.get(position).getBFiyat();
final int quantity = tableModelList.get(position).getAdet();
final int print = tableModelList.get(position).getYazdimi();
final String insertUrl = "This is URL for getting json array";
Map<String, String> parameters = new HashMap<>();
parameters.put("tableID", "" + getTableId);
parameters.put("rowID", "" + rowID);
parameters.put("treeID", ""+treeID);
parameters.put("process",""+process);
parameters.put("quantity",""+quantity);
parameters.put("price",""+price);
parameters.put("print",""+print);
CustomRequest jsObjRequest = new CustomRequest(Request.Method.POST, insertUrl, parameters, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray getOrders = response.getJSONArray("order");
Gson gson = new Gson();
tableModelList.clear();
for (int i = 0; i < getOrders.length(); i++) {
JSONObject order = getOrders.getJSONObject(i);
TableModel tableModel = gson.fromJson(order.toString(), TableModel.class);
tableModelList.add(tableModel);
}
mAdapter.notifyDataSetChanged();
System.out.println("**** onResponse: Request is done............");
System.out.println("**** JSON: "+response.toString());
dialog.cancel();
inProgress = false;
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError response) {
Log.d("Response: ", response.toString());
inProgress = false;
}
});
requestQueue.add(jsObjRequest);
}
}[/SIZE]
Dialog is showing when request beginning and canceling when request is done. But as I said, when I click faster, there is a delay between multiple requests even first request has already done. I'm saying 1 sec, because 2nd request is beginning after 1 sec exactly, no matter how I clicking fast. I can't figure it out..
I tested fast clicks to showing toasts with random numbers and it's working fine. But when I testing with JSON method, there is a weird delay.
I have SwipeRefreshLayout and ScrollView in my fragment. I'm using Volley with singleton.
Here is video to showing what my problem is;
Here is Logcat output for every click
Every fast click has returning success json output, but nothing change instantly on the screen..
Thanks for your help.

Related

[HELP] Filter SimpleAdapter / ListView

Hi, this is actually 2 questions.
I have a list of items stored in one string array and a list of the collections those items are in stored in a second string array.
I want the user to be able to search for an item and see in which collection it exists.
I have managed to do this in a less-than-elegant way by simply combining the 2 string arrays into one and using a ListView with a EditText with a TextWatcher to filter the results. This all works but the result is not so eye-pleasing. I use this to make the distinction between item and collections:
Code:
<item>ITEM \r\n -> COLLECTION(S)
when defining the string array.
As I said, it works but I would like the COLLECTION(S) to be formatted differently from the ITEM. Is this possible in a ListView?
This is my current code:
Code:
public class Search extends Activity {
/** Called when the activity is first created. */
private ListView lv1;
private EditText ed;
private String[] lv_arr;
private ArrayList<String> arr_sort= new ArrayList<String>();
int textlength=0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
lv1=(ListView)findViewById(R.id.listView1);
ed=(EditText)findViewById(R.id.editText1);
lv_arr = getResources().getStringArray(R.array.all_cont);
lv1.setAdapter(new ArrayAdapter<String>(this, R.layout.row , lv_arr));
ed.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
textlength=ed.getText().length();
arr_sort.clear();
for(int i=0;i<lv_arr.length;i++)
{
if(textlength<=lv_arr[i].length())
{
if(ed.getText().toString().equalsIgnoreCase((String) lv_arr[i].subSequence(0, textlength)))
{
arr_sort.add(lv_arr[i]);
}}}
lv1.setAdapter(new ArrayAdapter<String>(Search.this, R.layout.row , arr_sort));
}
});
}}
As a second solution that looks more elegant, I used a SimpleAdapter to put the 2 original string arrays in the ListView like this:
Code:
public class Search extends ListActivity {
private String[] l1;
private String[] l2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.seach);
ArrayList<Map<String, String>> list = buildData();
String[] from = { "name", "packs" };
int[] to = { android.R.id.text1, android.R.id.text2 };
SimpleAdapter adapter = new SimpleAdapter(this, list, android.R.layout.simple_list_item_2, from, to);
setListAdapter(adapter);}
private ArrayList<Map<String, String>> buildData() {
l1 = getResources().getStringArray(R.array.items);
l2 = getResources().getStringArray(R.array.packs);
Integer i;
int to = l1.length;
ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>();
for(i=0;i < to;i++){
list.add(putData(l1[i], l2[i]));
}
return list;
}
private HashMap<String, String> putData(String name, String packs) {
HashMap<String, String> item = new HashMap<String, String>();
item.put("name", name);
item.put("packs", packs);
return item;
}
}
This looks a lot better but I can't figure out how to make use of the EditText to filter the results.
Any help is welcomed!
Hey!
I read your post and I think it would be better to make a class like this:
Code:
public class ListItem
{
public String itemName;
public String collectionName;
}
And then in your Search activity you can Make a single ArrayList of the type ListItem. Populate this array in a way similar to how you are populating the ArrayList of the HashMaps.
Now for setting the ListAdapter you'll have to make a custom view for each row of the list(this custom row could contain two text views, one for the item name and the other for the collection and you can give them their own formatting), and then subclass the ArrayAdapter class and override its getView method.
Heres a couple of links that might be helpful:
http://www.ezzylearning.com/tutoria...droid-listview-items-with-custom-arrayadapter
http://stackoverflow.com/questions/2265661/how-to-use-arrayadaptermyclass
Hope this helps
The_R said:
Hey!
I read your post and I think it would be better to make a class like this:
Code:
public class ListItem
{
public String itemName;
public String collectionName;
}
And then in your Search activity you can Make a single ArrayList of the type ListItem. Populate this array in a way similar to how you are populating the ArrayList of the HashMaps.
Now for setting the ListAdapter you'll have to make a custom view for each row of the list(this custom row could contain two text views, one for the item name and the other for the collection and you can give them their own formatting), and then subclass the ArrayAdapter class and override its getView method.
Heres a couple of links that might be helpful:
http://www.ezzylearning.com/tutoria...droid-listview-items-with-custom-arrayadapter
http://stackoverflow.com/questions/2265661/how-to-use-arrayadaptermyclass
Hope this helps
Click to expand...
Click to collapse
Thanks once more. I looked over the links and I think I have an idea of how to adapt it to my app. Will try it tomorrow and let you know
Yeah. Let me know if it worked.
The_R said:
Yeah. Let me know if it worked.
Click to expand...
Click to collapse
I feel like my head is exploding.
I did what you said but I still have some issues. Here's what I did:
1. Created a new class, Icons:
Code:
public class Icons {
public String icon;
public String title;
public Icons(){
super();
}
public Icons(String icon, String title) {
super();
this.icon = icon;
this.title = title;
}
}
Created a new XML for the style of the ListView:
Code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/icon_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="3dp"
android:textSize="18sp"
android:textColor="#ffffff"
android:textStyle="bold" />
<TextView
android:id="@+id/in_pack"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:textSize="12sp" />
</LinearLayout>
created a new Adapter:
Code:
public class IconsAdapter extends ArrayAdapter<Icons>{
Context context;
int layoutResourceId;
Icons data[] = null;
public IconsAdapter(Context context, int layoutResourceId, Icons[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
IconsHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new IconsHolder();
holder.txtIcon = (TextView)row.findViewById(R.id.icon_name);
holder.txtTitle = (TextView)row.findViewById(R.id.in_pack);
row.setTag(holder);
}
else
{
holder = (IconsHolder)row.getTag();
}
Icons icons = data[position];
holder.txtTitle.setText(icons.title);
holder.txtIcon.setText(icons.icon);
return row;
}
static class IconsHolder
{
TextView txtIcon;
TextView txtTitle;
}
}
Modified my Search class like this:
Code:
public class Search extends Activity {
private ListView listView1;
private String[] l1;
private String[] l2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.seach);
l1 = getResources().getStringArray(R.array.items);
l2 = getResources().getStringArray(R.array.packs);
Integer i;
int to = l1.length;
// for(i=0;i < to;i++){}
Icons Icons_data[] = new Icons[]
{
new Icons(l1[0], l2[0]),
new Icons(l1[1], l2[1]),
new Icons(l1[2], l2[2]),
new Icons(l1[3], l2[3]),
};
IconsAdapter adapter = new IconsAdapter(this,
R.layout.row, Icons_data);
listView1 = (ListView)findViewById(R.id.listView1);
View header = (View)getLayoutInflater().inflate(R.layout.row, null);
listView1.addHeaderView(header);
listView1.setAdapter(adapter);
}
}
Up until now, everything works (almost) great. Only thing I can't do is figure out how to assign the items in the Icons_data[] array automatically (my for(...) statement doesn't seem to want to fit anywhere). Format looks good and manually inserting data does what it's supposed to. Still need to figure out the automatic data inserting thing...my arrays have 100-150 elements
What I also can't figure out is how the hell to perform the filtering/search on this new special Array... I tried using the old method with the TextWatcher on an EditText field but can't seem to be able to adapt this part:
Code:
public void onTextChanged(CharSequence s, int start, int before,
int count) {
textlength=ed.getText().length();
[B][U]arr_sort.clear();[/U][/B]
for(int i=0;i<to;i++)
{
if(textlength<=l1[i].length())
{
if(ed.getText().toString().equalsIgnoreCase((String) l1[i].subSequence(0, textlength)))
{
[B][U]arr_sort.add(l1[i]);[/U][/B]
}
}
}
[B][U]lv1.setAdapter(new ArrayAdapter<String>(Search.this, R.layout.row , arr_sort))[/U][/B];
}
});
ed is the EditText item. I guess I would need to make arr_sort of the type Icons[] and then change the Bold, Underlined lines to something...but no idea what... Is it even possible to do it like i'm doing it? Or should I look for another method to sort it?
Hey I modified your search class:
Code:
public class Search extends Activity {
private ListView listView1;
// Note: I've removed the two String[] class members cause we are going
// store this data in a single Icons[] member
private Icons[] iconsData;
private ArrayList<Icons> arr_sort; // Note: Changed the type of arr_sort
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.seach);
// We'll create two local String[] variables to assemble the data
String[] l1 = getResources().getStringArray(R.array.items);
String[] l2 = getResources().getStringArray(R.array.packs);
// get the total number of icons
int totalIcons = l1.length;
// Allocate the data for the Icon[] array
iconsData = new Icons[totalIcons];
// Now to populate the Icon array
for (int i = 0; i < totalIcons; i++)
{
iconsData[i] = new Icons(l1[i], l2[i]);
}
// Rest remains the same
IconsAdapter adapter = new IconsAdapter(this,
R.layout.row, iconsData);
listView1 = (ListView)findViewById(R.id.listView1);
View header = (View)getLayoutInflater().inflate(R.layout.row, null);
listView1.addHeaderView(header);
listView1.setAdapter(adapter);
}
}
Now you don't need to change the sorting method. Just slight modifications to fit the data structuring is all that is needed.
Code:
public void onTextChanged(CharSequence s, int start, int before, int count)
{
textlength = ed.getText().length();
arr_sort.clear();
for(int i = 0 ; i < to; i++)
{
if(textlength <= iconsData[i].icon.length()) //Note: l1 becomes iconsData[i].icon
{
if(ed.getText().toString().equalsIgnoreCase((String) iconsData[i].icon.subSequence(0, textlength)))
{
arr_sort.add(iconsData[i]); // Note: we'll store iconsData[i] if a match is found
}
}
}
lv1.setAdapter(new IconsAdapter(Search.this, R.layout.row , arr_sort.toArray()));
}
Haven't tested it. So watch out for some possible errors.
I can't thank you enough but I still need your help.
The first part works (modifications to the Search class).
Now, In the same class, after that part, I add the filtering part:
Code:
ed=(EditText)findViewById(R.id.editText1);
ed.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
int textlength = ed.getText().length();
arr_sort.clear();
for(int i=0;i<[B][I]totalIcons[/I][/B];i++)
{
if(textlength <= iconsData[i].icon.length()) //Note: l1 becomes iconsData[i].icon
{
if(ed.getText().toString().equalsIgnoreCase((String) iconsData[i].icon.subSequence(0, textlength)))
{
arr_sort.add(iconsData[i]); // Note: we'll store iconsData[i] if a match is found
}
}
}
listView1.setAdapter(new IconsAdapter(Search.this, R.layout.row , [U][B](Icons[])[/B][/U] arr_sort.toArray()));
}
});
}
}
I had to make 2 changes in order for it not to give any errors. First, I changed the "to" in the for statement to "totalIcons" since that's actually the number we need and "to" was not defined. When I did this I also had to change "totalIcons" to final int since I had this error:"Cannot refer to a non-final variable totalIcons inside an inner class defined in a different method"
Also, I had to add the (Icons[]) at the end because of this error: "The constructor IconsAdapter(Search, int, Object[]) is undefined". The suggested fixes was changing the constructor for IconsAdapter, adding a new constructor or adding the (Icons[]) thing.
Now I have no errors in Eclipse but when I run the app and try to type something in the EditText box the app crashes...I get these errors:
04-12 19:32:27.032: E/AndroidRuntime(998): FATAL EXCEPTION: main
04-12 19:32:27.032: E/AndroidRuntime(998): java.lang.NullPointerException
04-12 19:32:27.032: E/AndroidRuntime(998): at mmarin.iconpack.manager.Search$1.onTextChanged(Search.java:70)
04-12 19:32:27.032: E/AndroidRuntime(998): at android.widget.TextView.sendOnTextChanged(TextView.java:6295)
04-12 19:32:27.032: E/AndroidRuntime(998): at android.widget.TextView.handleTextChanged(TextView.java:6336)
04-12 19:32:27.032: E/AndroidRuntime(998): at android.widget.TextView$ChangeWatcher.onTextChanged(TextView.java:6485)
04-12 19:32:27.032: E/AndroidRuntime(998): at android.text.SpannableStringBuilder.sendTextChange(SpannableStringBuilder.java:889)
Sorry about the previous untested code. I was in a rush to go somewhere but I saw you online and thought that it'd be better if I replied.
Anyways, I think the problem is that "totalIcons" is a local variable. So remove the final keyword. And in the for loop in the TextWatcher's onTextChanged method instead of using totalIcons use the length property of iconsData:
Code:
for (int i = 0; i < iconsData.length; i++)
Should fix the runtime error
First off, please do all the things you have to do and don't waste your time with me. I really really appreciate you trying to help me so if you don't have time for this, it's absolutely no problem.
Now, the runtime errors are still there after the change
04-12 19:59:24.332: E/AndroidRuntime(1034): FATAL EXCEPTION: main
04-12 19:59:24.332: E/AndroidRuntime(1034): java.lang.NullPointerException
04-12 19:59:24.332: E/AndroidRuntime(1034): at mmarin.iconpack.manager.Search$1.onTextChanged(Search.java:70)
04-12 19:59:24.332: E/AndroidRuntime(1034): at android.widget.TextView.sendOnTextChanged(TextView.java:6295)
04-12 19:59:24.332: E/AndroidRuntime(1034): at android.widget.TextView.handleTextChanged(TextView.java:6336)
04-12 19:59:24.332: E/AndroidRuntime(1034): at android.widget.TextView$ChangeWatcher.onTextChanged(TextView.java:6485)
04-12 19:59:24.332: E/AndroidRuntime(1034): at mmarin.iconpack.manager.Search$1.onTextChanged(Sea rch.java:70)
Can you paste line 70 of Search.java?
Wait are you doing this in onCreate?
Code:
arr_sort = new ArrayList<Icons>();
That's what I was looking for (actually how to enable line numbers in Eclipse )
here it is:
Code:
arr_sort.clear();
Yep. We aren't creating arr_sort. So its a null pointer.
Do this somewhere in onCreate
Code:
arr_sort = new ArrayList<Icons>();
ok, that solved that issue. now the problem is with this:
Code:
listView1.setAdapter(new IconsAdapter(Search.this, R.layout.row, (Icons[]) arr_sort.toArray()));
What error/exception do you get?
04-12 20:17:26.663: E/AndroidRuntime(1205): FATAL EXCEPTION: main
04-12 20:17:26.663: E/AndroidRuntime(1205): java.lang.ClassCastException: [Ljava.lang.Object;
04-12 20:17:26.663: E/AndroidRuntime(1205): at mmarin.iconpack.manager.Search$1.onTextChanged(Search.java:84)
I guess that the arr_sort.toArray() creates an Object[] but we need a Icons[] resource for the IconsAdapter.
Am I close?
Yea you are right
One quick and ugly solution I can think of is maybe creating an Icons array right after the search and then filling it with all the items in the arraylist. This happens right before you are setting the adapter
Code:
Icons[] data = new Icons[arr_data.size()];
for (int i = 0; i < arr_data.size(); i++)
{
data[i] = arr_data.get(i);
}
listView1.setAdapter(new IconsAdapter(Search.this, R.layout.row, data));
This should work but it isn't really a good solution =/
Quick and ugly works for me! You're 3 for 3!
You get a big special thanks in my App!!!
Once more, thank you and probably I will ask for your help again in a short while, with another issue I can't figure out.
It will probably be about getting a market link for an app through the Share menu in the Play Store and using that information to send an e-mail - but I will try to figure it out for myself . I already found how to get my app in the "Share" menu in the Play Store and also (possibly) how to save that information to a string. Now i have to find out how to actually get my app to start a certain Activity when it is started by the Play Store app. Will do that over the weekend
Sure! I'll be happy to help out with whatever little bit know!

[Q] App Developers:GET contenet from custom Expandablelistview

Hi,
I searched for a part to ask questions abut android programing but cant find so I posted here,I hope I can find my answer
I am new with android programing and I have a problem with expandable list view
I pupulate my data to an expandable list view with SimpleExpandableListAdapter and every thing is good..The only think I want is to findout which Items is selected by user..I searched but Cant fine a working method to do this
here Is my SimpleExpandableListAdapter
Code:
SimpleExpandableListAdapter expListAdapter =
new SimpleExpandableListAdapter(
this,
groupData,
android.R.layout.simple_expandable_list_item_1,
new String[] { "grup"},
new int[] { android.R.id.text1 },
childData,
R.layout.database_list_item,
new String[] { parser.KEY_CatName, parser.KEY_PoetID, parser.KEY_DownloadUrl,parser.KEY_PubDate,parser.KEY_FileSizeInByte,"Status"},
new int[] { R.id.chk_database_list_item,R.id.txt_database_poet_id,R.id.txt_database_download_link,R.id.txt_database_pub_date,R.id.txt_database_size,R.id.txt_database_status }
);
and here Is setOnChildClickListener but It dont do anything
Code:
ExpandList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView arg0, View v, int arg2,
int arg3, long arg4) {
Log.i("setOnChildClickListener", "setOnChildClickListener");
TextView down_link = (TextView) v.findViewById(R.id.txt_database_download_link);
TextView poet_id = (TextView) v.findViewById(R.id.txt_database_poet_id);
String down_linkString;
String poet_idString;
SparseBooleanArray choices = arg0.getCheckedItemPositions();
StringBuilder choicesString = new StringBuilder();
for (int i = 0; i < choices.size(); i++)
{
//added if statement to check for true. The SparseBooleanArray
//seems to maintain the keys for the checked items, but it sets
//the value to false. Adding a boolean check returns the correct result.
//ArrayList<String> Items_for_download = new ArrayList<String>();
if(choices.valueAt(i) == true)
choicesString.append(poet_id.getText().toString()).append(" ");
}
Log.i("selected", choicesString.toString());
return false;
}
});
Thanks for your helps

[Q] can't transform xml+xsl(with exslt) to html

Hi guys, I am developing an app which loads a xml and a xsl and loads the resulting html, displaying it on the screen. It works perfectly when the xsl does not have exslt functions. However, when it does contain exslt functions, it doesn't work.
The code is rather small, so I'm posting it here:
Code:
public class MainActivity extends Activity {
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView webview = new WebView(this);
setContentView(webview);
Source xmlSource = new StreamSource(this.getResources().openRawResource(R.raw.xml2));
Source xsltSource = new StreamSource(this.getResources().openRawResource(R.raw.xsl2));
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = null;
ByteArrayOutputStream output = null;
StreamResult result;
try
{
transformer = tFactory.newTransformer(xsltSource);
output = new ByteArrayOutputStream();
result = new StreamResult(output);
transformer.transform(xmlSource, result);
} catch (TransformerException e)
{
e.printStackTrace();
}
ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());
String html = new Scanner(input,"UTF-8").useDelimiter("\\A").next();
webview.loadData(html, "text/html", "UTF-8");
}
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
I have attached a zip file containing 5 files: xml,xsl, xml2,xsl2, logcat.
I get the errors with xml2 and xsl2.
I'm using the eclipse IDE, ADT bundle thing. In addition, I have tried an equivalent code in netbeans:
Code:
public class JavaApplication4 {
/**
* [user=955119]@param[/user] args the command line arguments
*/
public static void main(String[] args) throws TransformerConfigurationException, TransformerException, FileNotFoundException {
Source xmlSource = new StreamSource("xml2.xml");
Source xsltSource = new StreamSource("xsl2.xsl");
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer(xsltSource);
ByteArrayOutputStream output = new ByteArrayOutputStream();
StreamResult result = new StreamResult(output);
transformer.transform(xmlSource, result);
ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());
String html = new Scanner(input,"UTF-8").useDelimiter("\\A").next();
System.out.println(html);
}
}
which, to my surprise, works for both xml and xsl.
Please help me, I've been trying to make it work for hours...I've tried many stuff, different codes...but it doesn't seem to have anything to do with my code.
Thank you for your time.

[Q] How do I filter a retrieve data in Spinner?

I'm new to android,stuck in this part of my code.
I do hope, someone would help me with it.
As ,I've stuck for quite a while and have to complete within 2 days,
If I would like to filter in spinner based on the dates, how should I do it? For example,
I've a list of events, and in my spinner
when I select "Today", it will show out the list for today.
I've tried out the coding, however, I met some error. The part in BOLD, ** is having error.
I would like to get the XML data from here:
[attached in this thread]
the highlighted part
here is my coding: AndroidXMLParsingActivity.java
public class AndroidXMLParsingActivity extends ListActivity implements OnItemSelectedListener {
String[] browseby;
String[] dates = { "Today", "Tomorrow", "Next Week",
};
ArrayList<String> browse = new ArrayList<String>();
ArrayList<String> mPostingData = new ArrayList<String>();
Spinner s1;
ListView listview;
CustomAdapter cus;
// All static variables
static final String URL = " URL ";
// XML node keys
static final String KEY_EVENT = "event"; // parent node
static final String KEY_TITLE = "title";
static final String KEY_START_TIME = "start_time";
@override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_EVENT);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_START_TIME, parser.getValue(e, KEY_START_TIME));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item, new String[] { KEY_TITLE,KEY_START_TIME }, new int[] {
R.id.title,
R.id.startTime });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
@override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String title = ((TextView) view.findViewById(R.id.title))
.getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
SingleMenuItemActivity.class);
in.putExtra(KEY_TITLE, title);
startActivity(in);
}
});
listview = (ListView) findViewById(R.id.listView1);
s1 = (Spinner) findViewById(R.id.spinner1);
for (int i = 0; i < browseby.length; i++) {
browse.add(browseby);
}
// aa = new
// ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,Category);
s1.setOnItemSelectedListener(this);
mPostingData = browse;
for (int i = 0; i < mPostingData.size(); i++) {
if (mPostingData.size() > 0)
Log.i("Datas", mPostingData.get(i));
}
cus = new CustomAdapter(this, 0);
setListAdapter(cus);
ArrayAdapter<String> aa = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, dates);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(aa);
}
public void onItemSelected(AdapterView<?> parent, View v, int position,
long id) {
// listview.setFilterText(Category[position]);
String Text = s1.getSelectedItem().toString();
cus.getFilter().filter(Text);
cus.notifyDataSetChanged();
}
public void onNothingSelected(AdapterView<?> parent) {
// listview.setFilterText("");
}
public void onListItemClick(ListView parent, View v, int position, long id) {
Toast.makeText(this, "You have selected " + mPostingData.get(position),
Toast.LENGTH_SHORT).show();
}
class CustomAdapter extends ArrayAdapter<String> {
public void setData(ArrayList<String> mPpst) {
mPostingData = mPpst;// contains class items data.
}
@override
******public Filter getFilter() {
return new Filter() {
@override
protected void publishResults(CharSequence constraint,
FilterResults start_time) {
if (start_time.equals("2013-09-25") {
setData((ArrayList<String>) start_time.values);
} else {
setData(browse);// set original values
}
notifyDataSetInvalidated();
}******
@override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults result = new FilterResults();
if (!TextUtils.isEmpty(constraint)) {
constraint = constraint.toString();
ArrayList<String> foundItems = new ArrayList<String>();
if (browse != null) {
for (int i = 0; i < browse.size(); i++) {
if (browse.get(i).contains(constraint)) {
System.out.println("My datas" + browse.get(i));
foundItems.add(browse.get(i));
} else {
}
}
}
result.count = foundItems.size();// search results found
// return count
result.values = foundItems;// return values
} else {
result.count = -1;// no search results found
}
return result;
}
};
}
LayoutInflater mInflater;
public CustomAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
// TODO Auto-generated constructor stub
mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@override
public int getCount() {
// TODO Auto-generated method stub
return mPostingData.size();
}
@override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder vh;
if (convertView == null) {
vh = new ViewHolder();
convertView = mInflater.inflate(R.layout.row, null);
vh.t1 = (TextView) convertView.findViewById(R.id.textView1);
convertView.setTag(vh);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
vh = (ViewHolder) convertView.getTag();
}
if (mPostingData.size() > 0)
vh.t1.setText(mPostingData.get(position));
return convertView;
}
}
static class ViewHolder {
TextView t1;
}
}
randomise said:
I'm new to android,stuck in this part of my code.
I do hope, someone would help me with it.
As ,I've stuck for quite a while and have to complete within 2 days,
If I would like to filter in spinner based on the dates, how should I do it? For example,
I've a list of events, and in my spinner
when I select "Today", it will show out the list for today.
I've tried out the coding, however, I met some error. The part in BOLD, ** is having error.
I would like to get the XML data from here:
[attached in this thread]
the highlighted part
here is my coding: AndroidXMLParsingActivity.java
public class AndroidXMLParsingActivity extends ListActivity implements OnItemSelectedListener {
String[] browseby;
String[] dates = { "Today", "Tomorrow", "Next Week",
};
ArrayList<String> browse = new ArrayList<String>();
ArrayList<String> mPostingData = new ArrayList<String>();
Spinner s1;
ListView listview;
CustomAdapter cus;
// All static variables
static final String URL = " URL ";
// XML node keys
static final String KEY_EVENT = "event"; // parent node
static final String KEY_TITLE = "title";
static final String KEY_START_TIME = "start_time";
@override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_EVENT);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_START_TIME, parser.getValue(e, KEY_START_TIME));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item, new String[] { KEY_TITLE,KEY_START_TIME }, new int[] {
R.id.title,
R.id.startTime });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
@override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String title = ((TextView) view.findViewById(R.id.title))
.getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
SingleMenuItemActivity.class);
in.putExtra(KEY_TITLE, title);
startActivity(in);
}
});
listview = (ListView) findViewById(R.id.listView1);
s1 = (Spinner) findViewById(R.id.spinner1);
for (int i = 0; i < browseby.length; i++) {
browse.add(browseby);
}
// aa = new
// ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,Category);
s1.setOnItemSelectedListener(this);
mPostingData = browse;
for (int i = 0; i < mPostingData.size(); i++) {
if (mPostingData.size() > 0)
Log.i("Datas", mPostingData.get(i));
}
cus = new CustomAdapter(this, 0);
setListAdapter(cus);
ArrayAdapter<String> aa = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, dates);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(aa);
}
public void onItemSelected(AdapterView<?> parent, View v, int position,
long id) {
// listview.setFilterText(Category[position]);
String Text = s1.getSelectedItem().toString();
cus.getFilter().filter(Text);
cus.notifyDataSetChanged();
}
public void onNothingSelected(AdapterView<?> parent) {
// listview.setFilterText("");
}
public void onListItemClick(ListView parent, View v, int position, long id) {
Toast.makeText(this, "You have selected " + mPostingData.get(position),
Toast.LENGTH_SHORT).show();
}
class CustomAdapter extends ArrayAdapter<String> {
public void setData(ArrayList<String> mPpst) {
mPostingData = mPpst;// contains class items data.
}
@override
******public Filter getFilter() {
return new Filter() {
@override
protected void publishResults(CharSequence constraint,
FilterResults start_time) {
if (start_time.equals("2013-09-25") {
setData((ArrayList<String>) start_time.values);
} else {
setData(browse);// set original values
}
notifyDataSetInvalidated();
}******
@override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults result = new FilterResults();
if (!TextUtils.isEmpty(constraint)) {
constraint = constraint.toString();
ArrayList<String> foundItems = new ArrayList<String>();
if (browse != null) {
for (int i = 0; i < browse.size(); i++) {
if (browse.get(i).contains(constraint)) {
System.out.println("My datas" + browse.get(i));
foundItems.add(browse.get(i));
} else {
}
}
}
result.count = foundItems.size();// search results found
// return count
result.values = foundItems;// return values
} else {
result.count = -1;// no search results found
}
return result;
}
};
}
LayoutInflater mInflater;
public CustomAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
// TODO Auto-generated constructor stub
mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@override
public int getCount() {
// TODO Auto-generated method stub
return mPostingData.size();
}
@override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder vh;
if (convertView == null) {
vh = new ViewHolder();
convertView = mInflater.inflate(R.layout.row, null);
vh.t1 = (TextView) convertView.findViewById(R.id.textView1);
convertView.setTag(vh);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
vh = (ViewHolder) convertView.getTag();
}
if (mPostingData.size() > 0)
vh.t1.setText(mPostingData.get(position));
return convertView;
}
}
static class ViewHolder {
TextView t1;
}
}
Click to expand...
Click to collapse
Can someone please help me out?
your help will be appreciated.
Thanks

[Q] Google Map is Not Working in Android Emulator.

Hi there
I am trying to Run google Map on Android Emulator But Map is Not Working.I mean Google Map is displaying in Fragment But there is Not any Markers that I place in My Code.
This is My activity class
Java:
double mLatitude=0;
double mLongitude=0;
private GoogleMap map;
Spinner mSprPlaceType;
String[] mPlaceType=null;
String[] mPlaceTypeName=null;
[user=5448622]@Suppress[/user]Lint("NewApi")
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_places1);
// Array of place types
mPlaceType = getResources().getStringArray(R.array.place_type);
// Array of place type names
mPlaceTypeName = getResources().getStringArray(R.array.place_type_name);
// Creating an array adapter with an array of Place types
// to populate the spinner
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, mPlaceTypeName);
// Getting reference to the Spinner
mSprPlaceType = (Spinner) findViewById(R.id.spr_place_type);
// Setting adapter on Spinner to set place types
mSprPlaceType.setAdapter(adapter);
Button btnFind;
// Getting reference to Find Button
btnFind = ( Button ) findViewById(R.id.button1);
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}
else
{
map=((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
map.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location From GPS
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
// Setting click event lister for the find button
btnFind.setOnClickListener(new OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
int selectedPosition = mSprPlaceType.getSelectedItemPosition();
String type = mPlaceType[selectedPosition];
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location="+mLatitude+","+mLongitude);
sb.append("&radius=10000");
sb.append("&types="+type);
sb.append("&sensor=true");
sb.append("&key=AIzaSyCba6q28XzWhcq5wPaB7ek7HWqh3Sq2Q3A");
// Creating a new non-ui thread task to download json data
PlacesTask placesTask = new PlacesTask();
// Invokes the "doInBackground()" method of the class PlaceTask
placesTask.execute(sb.toString());
}
});
}
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
/** A class, to download Google Places */
private class PlacesTask extends AsyncTask<String, Integer, String>{
String data = null;
// Invoked by execute() method of this object
[user=439709]@override[/user]
protected String doInBackground(String... url) {
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
// Executed after the complete execution of doInBackground() method
[user=439709]@override[/user]
protected void onPostExecute(String result){
ParserTask parserTask = new ParserTask();
// Start parsing the Google places in JSON format
// Invokes the "doInBackground()" method of the class ParseTask
parserTask.execute(result);
}
}
/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{
JSONObject jObject;
// Invoked by execute() method of this object
[user=439709]@override[/user]
protected List<HashMap<String,String>> doInBackground(String... jsonData) {
List<HashMap<String, String>> places = null;
PlaceJSONParser placeJsonParser = new PlaceJSONParser();
try{
jObject = new JSONObject(jsonData[0]);
/** Getting the parsed data as a List construct */
places = placeJsonParser.parse(jObject);
}catch(Exception e){
Log.d("Exception",e.toString());
}
return places;
}
// Executed after the complete execution of doInBackground() method
[user=439709]@override[/user]
protected void onPostExecute(List<HashMap<String,String>> list){
// Clears all the existing markers
map.clear();
for(int i=0;i<list.size();i++){
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Getting a place from the places list
HashMap<String, String> hmPlace = list.get(i);
// Getting latitude of the place
double lat = Double.parseDouble(hmPlace.get("lat"));
// Getting longitude of the place
double lng = Double.parseDouble(hmPlace.get("lng"));
// Getting name
String name = hmPlace.get("place_name");
// Getting vicinity
String vicinity = hmPlace.get("vicinity");
LatLng latLng = new LatLng(lat, lng);
// Setting the position for the marker
markerOptions.position(latLng);
// Setting the title for the marker.
//This will be displayed on taping the marker
markerOptions.title(name + " : " + vicinity);
// Placing a marker on the touched position
map.addMarker(markerOptions);
}
}
}
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.show_places1, menu);
return true;
}
[user=439709]@override[/user]
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
[user=439709]@override[/user]
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
mLatitude=location.getLatitude();
mLongitude=location.getLongitude();
LatLng latLng = new LatLng(mLatitude, mLongitude);
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
map.animateCamera(CameraUpdateFactory.zoomTo(12));
}
[user=439709]@override[/user]
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
[user=439709]@override[/user]
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
[user=439709]@override[/user]
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
}
And This is My Emulator Defination
Phone_Test2
Nexus S(4.0,480*800hdpi)
Google API(x86 System Image)
Intel Atomx86
HVGA
RAM:500MB
VM Heap:16
Internal Storage:200
SD Card:50
Click to expand...
Click to collapse
I have added all Jars and Permisiion in Manifest.Application is Working fine on Android Powerd Mobile Phone But Not on Android Emulator
any guess?
Thanks

Categories

Resources