Related
Hi everyone,
I am currently working on my first app which grabs a ZIP from the internet and the extracts it to a certain location. Everything works great but I can not figure out how to show a Toast message when the extraction operation is done.
The code I am using for unzipping is:
Code:
package mmarin.test.download;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
*
* @author jon
*/
public class Decompress{
private String _zipFile;
private String _location;
byte[] buffer = new byte[1024];
int length;
public Decompress(String zipFile, String location) {
_zipFile = zipFile;
_location = location;
_dirChecker("");
}
public void unzip() {
try {
FileInputStream fin = new FileInputStream(_zipFile);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
Log.v("Decompress", "Unzipping " + ze.getName());
if(ze.isDirectory()) {
_dirChecker(ze.getName());
} else {
FileOutputStream fout = new FileOutputStream(_location + ze.getName());
while ((length = zin.read(buffer))>0) {
fout.write(buffer, 0, length);
}
zin.closeEntry();
fout.close();
}
}
zin.close();
} catch(Exception e) {
Log.e("Decompress", "unzip", e);
}
}
private void _dirChecker(String dir) {
File f = new File(_location + dir);
if(!f.isDirectory()) {
f.mkdirs();
}
}
}
I am calling the Decompress activity through a button:
Code:
Button decompress = (Button)findViewById(R.id.button1);
decompress.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
String zipFile = Environment.getExternalStorageDirectory() + "/IPM/Splash.zip";
String unzipLocation = Environment.getExternalStorageDirectory() + "/IPM/Splash/";
Decompress d = new Decompress(zipFile, unzipLocation);
d.unzip();
}
});
I found this here: http://www.jondev.net/articles/Unzipping_Files_with_Android_(Programmatically) and it works great.
As I said above, only issue is displaying a message that everything is done.
Can someone please help me out?
Thank you!
Please use the Q&A Forum for questions &
Read the Forum Rules Ref Posting
Moving to Q&A
Put the toast after zin.close()
www.stackoverflow.com
Here you can find what you want
Xperian using xda app
http://stackoverflow.com/questions/9824772/toast-after-email-intent-message
Check this
Xperian using xda app
RoberGalarga said:
Put the toast after zin.close()
Click to expand...
Click to collapse
Hey,
I tried this but it doesn't work. I used this statement:
Code:
Toast.makeText(this, "Extraction complete", "LENGTH_SHORT").show();
and I got this error message: The method makeText(Context, CharSequence, int) in the type Toast is not applicable for the arguments (Decompress, String, String).
Help?
The method makeText(Context, CharSequence, int) in the type Toast is not applicable for the arguments (Decompress, String, String)
What the above line means is that you need to pass a Context object, a CharSequence object and an int. You are passing the wrong object types (Decompress, String, String).
The example you saw used the Toast in the activity class itself, that is why the first value passed was a this. The "LENGTH_SHORT" is actually a constant Toast.LENGTH_SHORT.
I am guessing you are making the button object in your main activity class. So i'd suggest making an additional method for the activity class that looks like this
Code:
public void displayToast(CharSequence cs)
{
Toast.makeText(this, cs, Toast.LENGTH_SHORT).show();
}
and then make the following change to your code
Code:
Button decompress = (Button)findViewById(R.id.button1);
decompress.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
String zipFile = Environment.getExternalStorageDirectory() + "/IPM/Splash.zip";
String unzipLocation = Environment.getExternalStorageDirectory() + "/IPM/Splash/";
Decompress d = new Decompress(zipFile, unzipLocation);
d.unzip();
// Add the following line
displayToast("Unzip complete");
}
});
Let me know if it worked for you.
The_R said:
The method makeText(Context, CharSequence, int) in the type Toast is not applicable for the arguments (Decompress, String, String)
What the above line means is that you need to pass a Context object, a CharSequence object and an int. You are passing the wrong object types (Decompress, String, String).
The example you saw used the Toast in the activity class itself, that is why the first value passed was a this. The "LENGTH_SHORT" is actually a constant Toast.LENGTH_SHORT.
I am guessing you are making the button object in your main activity class. So i'd suggest making an additional method for the activity class that looks like this
Code:
public void displayToast(CharSequence cs)
{
Toast.makeText(this, cs, Toast.LENGTH_SHORT).show();
}
and then make the following change to your code
Code:
Button decompress = (Button)findViewById(R.id.button1);
decompress.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
String zipFile = Environment.getExternalStorageDirectory() + "/IPM/Splash.zip";
String unzipLocation = Environment.getExternalStorageDirectory() + "/IPM/Splash/";
Decompress d = new Decompress(zipFile, unzipLocation);
d.unzip();
// Add the following line
displayToast("Unzip complete");
}
});
Let me know if it worked for you.
Click to expand...
Click to collapse
PERFECT! You're amazing!
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!
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
Hi! So Im about to release two versions of my app, one free with ads and one for 99cent. I followed Marios instuctions on how to add AdMob for Libgdx so I ended up with this:
Code:
public class MainActivity extends AndroidApplication implements IActivityRequestHandler {
protected AdView adView;
private final int SHOW_ADS = 1;
private final int HIDE_ADS = 0;
protected Handler handler = new Handler()
{
@Override
public void handleMessage(Message msg) {
switch(msg.what) {
case SHOW_ADS:
{
adView.setVisibility(View.VISIBLE);
break;
}
case HIDE_ADS:
{
adView.setVisibility(View.GONE);
break;
}
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create the layout
RelativeLayout layout = new RelativeLayout(this);
// Do the stuff that initialize() would do for you
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
// Create the libgdx View
View gameView = initializeForView(new Game(this), false);
// Create and setup the AdMob view
adView = new AdView(this, AdSize.BANNER, "secretKey"); // Put in your secret key here
adView.loadAd(new AdRequest());
// Add the libgdx view
layout.addView(gameView);
// Add the AdMob view
RelativeLayout.LayoutParams adParams =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
adParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
adParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
layout.addView(adView, adParams);
// Hook it all up
setContentView(layout);
}
@Override
public void showAds(boolean show) {
handler.sendEmptyMessage(show ? SHOW_ADS : HIDE_ADS);
}
}
My question is, since Im going to have a adfree version and I want to make it as easy as possible, can I just call "handler.showAds(false);" to completely dissable ads in the paid version or should I completely remove everything that have to do with the ads? I don't know much about how the ads works and Im afraid there will be some mix up since I read something about impressions might go wrong and stuff
I changed it to this, will this work?
Code:
public class MainActivity extends AndroidApplication implements IActivityRequestHandler {
protected AdView adView;
private final int SHOW_ADS = 1;
private final int HIDE_ADS = 0;
private boolean isBought = false;
protected Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch(msg.what) {
case SHOW_ADS:
{
adView.setVisibility(View.VISIBLE);
break;
}
case HIDE_ADS:
{
adView.setVisibility(View.GONE);
break;
}
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create the layout
RelativeLayout layout = new RelativeLayout(this);
// Do the stuff that initialize() would do for you
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
// Create the libgdx View
View gameView = initializeForView(new Game(this, isBought), false);
// Create and setup the AdMob view
if(!isBought){
adView = new AdView(this, AdSize.BANNER, "Secret Key"); // Put in your secret key here
adView.loadAd(new AdRequest());
}
// Add the libgdx view
layout.addView(gameView);
// Add the AdMob view
if(!isBought){
RelativeLayout.LayoutParams adParams =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
adParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
adParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
layout.addView(adView, adParams);
}
// Hook it all up
setContentView(layout);
}
@Override
public void showAds(boolean show) {
handler.sendEmptyMessage(show ? SHOW_ADS : HIDE_ADS);
}
}
Okay, so I have the fix for this, but I have another problem now. I had to create two different android projects (both linked to the main source of the game) with a ".free" at the free versions packaging name in the AndroidManifest, because you cant have two apps with the same packaging on Google Play. But this makes it so that the user have to restart everything if they upgrade from the free version to paid version.
All I want to is that I could save the preference file to a specific place (so it wont get removed if the free version gets removed) and make the paid version read it. And Im using LibGdx btw Smiley
EDIT:
I have tried doing it now with using Context. I'm able to find the preference file, but it's not able to get the contents from the preference file itself, since it always returns 0 (the default value). Is this because I use LibGdx? I have read that LibGdx saves its own preference files as SharedPreferences on Android so that shouldn't be the issue.
Code:
public void tryLoadPrefs(){
Context otherAppsContext = null;
try {
otherAppsContext = createPackageContext("com.mayogames.zombiecubes.free", 0);
} catch (NameNotFoundException e) {
System.out.println(e);
}
System.out.println("Extracting = " + otherAppsContext.getSharedPreferences("Settings", CONTEXT_IGNORE_SECURITY).getInt("seconds", 0));
}
Delta517 said:
Okay, so I have the fix for this, but I have another problem now. I had to create two different android projects (both linked to the main source of the game) with a ".free" at the free versions packaging name in the AndroidManifest, because you cant have two apps with the same packaging on Google Play. But this makes it so that the user have to restart everything if they upgrade from the free version to paid version.
All I want to is that I could save the preference file to a specific place (so it wont get removed if the free version gets removed) and make the paid version read it. And Im using LibGdx btw Smiley
EDIT:
I have tried doing it now with using Context. I'm able to find the preference file, but it's not able to get the contents from the preference file itself, since it always returns 0 (the default value). Is this because I use LibGdx? I have read that LibGdx saves its own preference files as SharedPreferences on Android so that shouldn't be the issue.
Code:
public void tryLoadPrefs(){
Context otherAppsContext = null;
try {
otherAppsContext = createPackageContext("com.mayogames.zombiecubes.free", 0);
} catch (NameNotFoundException e) {
System.out.println(e);
}
System.out.println("Extracting = " + otherAppsContext.getSharedPreferences("Settings", CONTEXT_IGNORE_SECURITY).getInt("seconds", 0));
}
Click to expand...
Click to collapse
EDIT: Im loading in the onCreate() method. Is that a problem?
Personally, the way I do it with libGDX is I create two projects. One with the adds and one without, like you said.
To solve the problem of not having two projects with the same package name, I change the second one. Then go into the android manifest file and change it there too. Then it should work.
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