[Q] How to use multi-threaded class in bootanimation? - Android Q&A, Help & Troubleshooting

Hi Droid-expert
For stock bootanimation in JB, there is a single threaded animation process/class inside. If I'd like to implement the power-on sound/tune as well. What's the best programming scheme/model it could be?
So far, by my understanding, I did something in BootAnimation.cpp in the following:
Did I do wrong? The handset boots up, it shows the animation first, and then the sound is played.
However, in a normal AOS adb shell session, try to run bootanimation, and it works fine (I mean both animation and sound are played at the same time)
Does the init is multi-threaded?
Anthony
class PlayerListener: public MediaPlayerListener, public Thread
{
public:
PlayerListener(): Thread(false), mp(NULL) {}
~PlayerListener() { delete mp; mp = NULL; }
virtual void notify(int, int, int, const Parcel *) {}
virtual bool threadLoop();
virtual status_t readyToRun();
private:
MediaPlayer* mp;
};
// ----------------------------------------------------------------------
bool PlayerListener::threadLoop()
{
if (mp != NULL)
mp->start();
sleep(100);
requestExit();
return false;
}
status_t PlayerListener::readyToRun()
{
int index = 7;
audio_devices_t device;
bool r;
mp = new MediaPlayer();
mp->setListener(this);
if (mp->setDataSource(SYSTEM_BOOTANIMATION_SOUND_FILE, NULL) == NO_ERROR) {
mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
mp->prepare();
mp->setLooping(false);
}
// AudioSystem::getStreamVolumeIndex(AUDIO_STREAM_ENFORCED_AUDIBLE, &index);
device = AudioSystem::getDevicesForStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
r = AudioSystem::setStreamVolumeIndex(AUDIO_STREAM_ENFORCED_AUDIBLE, index, device);
r = AudioSystem::getStreamVolumeIndex(AUDIO_STREAM_ENFORCED_AUDIBLE, &index, device);
if (index != 0) {
mp->seekTo(0);
// mp->start();
}
return NO_ERROR;
}
bool BootAnimation::threadLoop()
{
bool r;
sp<PlayerListener> player = new PlayerListener();
player->run("BootAnimatedMelody", PRIORITY_AUDIO);
if (mAndroidAnimation) {
r = android();
} else {
r = movie();
}

Related

[Q] Get Android build number in app

Hi there,
I am writing an app and for one of the features I need the firmware build number.
I know I can get the firmware version(like 4.1.1) with android.os.build but I need the build number of a rom(like "Rom version 1.0") thats stored in build.prop. I know I can parse the whole build.prop file and extract the 1 string of information but is there another way to get is faster and that it doesnt require root to use?
Grtz,
Thirith
Solved it
I solved my own question
Here is how I did it(in case somebody wants to achieve the same thing):
Code:
TextView tv = (TextView)findViewById(R.id.text1);
String input = "getprop |awk -F : '/build.display.id/ { print $2 }'";
execCommandLine(input, tv);
void execCommandLine(String command, TextView tv)
{
Runtime runtime = Runtime.getRuntime();
Process proc = null;
OutputStreamWriter osw = null;
// Running the Script
try
{
proc = runtime.exec("su");
osw = new OutputStreamWriter(proc.getOutputStream());
osw.write(command);
osw.flush();
osw.close();
}
// If return error
catch (IOException ex)
{
// Log error
Log.e("execCommandLine()", "Command resulted in an IO Exception: " + command);
return;
}
// Try to close the process
finally
{
if (osw != null)
{
try
{
osw.close();
}
catch (IOException e){}
}
}
try
{
proc.waitFor();
}
catch (InterruptedException e){}
// Display on screen if error
if (proc.exitValue() != 0)
{
Log.e("execCommandLine()", "Command returned error: " + command + "\n Exit code: " + proc.exitValue());
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage(command + "\nWas not executed sucessfully!");
builder.setNeutralButton("OK", null);
AlertDialog dialog = builder.create();
dialog.setTitle("Script Error");
dialog.show();
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(proc.getInputStream()));
int read;
char[] buffer = new char[4096];
StringBuffer output = new StringBuffer();
try {
while ((read = reader.read(buffer)) > 0) {
output.append(buffer, 0, read);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String exit = output.toString();
if(exit != null && exit.length() == 0) {
exit = "Command executed Successfully but no output was generated";
}
tv.setText(exit);
}
Hi, thanks for making your code public!
Just got an error when trying your code into my app.
Line
Code:
execCommandLine(input, tv);
runs into this error:
Multiple markers at this line
- input cannot be resolved to a type
- Return type for the method is missing
- Syntax error on token ",", delete this
token
Click to expand...
Click to collapse
How do I fix it?
Ok, did a mistake with integrating the code. My whole activity:
Code:
package de.yanniks.cm_updatechecker;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import de.yanniks.cm_updatechecker.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class UpdateChecker extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.updatecheck);
TextView tv = (TextView)findViewById(R.id.installedversion);
String input = "getprop |awk -F : '/build.display.id/ { print $2 }'";
execCommandLine(input, tv);}
void execCommandLine(String command, TextView tv)
{
Runtime runtime = Runtime.getRuntime();
Process proc = null;
OutputStreamWriter osw = null;
// Running the Script
try
{
proc = runtime.exec("su");
osw = new OutputStreamWriter(proc.getOutputStream());
osw.write(command);
osw.flush();
osw.close();
}
// If return error
catch (IOException ex)
{
// Log error
Log.e("execCommandLine()", "Command resulted in an IO Exception: " + command);
return;
}
// Try to close the process
finally
{
if (osw != null)
{
try
{
osw.close();
}
catch (IOException e){}
}
}
try
{
proc.waitFor();
}
catch (InterruptedException e){}
// Display on screen if error
if (proc.exitValue() != 0)
{
Log.e("execCommandLine()", "Command returned error: " + command + "\n Exit code: " + proc.exitValue());
AlertDialog.Builder builder = new AlertDialog.Builder(UpdateChecker.this);
builder.setMessage(command + "\nWas not executed sucessfully!");
builder.setNeutralButton("OK", null);
AlertDialog dialog = builder.create();
dialog.setTitle("Script Error");
dialog.show();
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(proc.getInputStream()));
int read;
char[] buffer = new char[4096];
StringBuffer output = new StringBuffer();
try {
while ((read = reader.read(buffer)) > 0) {
output.append(buffer, 0, read);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String exit = output.toString();
if(exit != null && exit.length() == 0) {
exit = "Command executed Successfully but no output was generated";
}
tv.setText(exit);
}
}
A better solution is to use my SystemProperties.get("build.display.id") directly instead of forking a native binary.
Code:
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.ByteOrder;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
public class SystemProperties {
public static final int PROP_NAME_MAX= 32; // sic
public static final int PROP_VALUE_MAX= 92; // sic
public static final int PROP_AREA_MAGIC= 0x504f5250; // "PROP"
public static final int PROP_AREA_VERSION= 0x45434f76; // "vOCE" (API level 3..8 at least)
public static final String PROP_SERVICE_NAME= "property_service";
public static final String WORKSPACE= "ANDROID_PROPERTY_WORKSPACE";
// prop_area struct
public static final int PA_COUNT= 0;
public static final int PA_SERIAL= 4;
public static final int PA_MAGIC= 8;
public static final int PA_VERSION= 12;
public static final int PA_RESERVED= 16;
public static final int PA_TOC= 32;
public static final int PA_INFO_NAME= 0;
public static final int PA_INFO_SERIAL= PA_INFO_NAME+PROP_NAME_MAX;
public static final int PA_INFO_VALUE= PA_INFO_SERIAL+4;
private static MappedByteBuffer mMap= null;
private static boolean init() throws IllegalArgumentException,
SecurityException,
NoSuchFieldException,
IllegalAccessException,
IOException {
FileDescriptor fd;
MappedByteBuffer mbb= null;
String workspace= System.getenv(WORKSPACE);
if (workspace == null) {
throw new IllegalArgumentException(WORKSPACE + " not set");
}
String[] wsArray= workspace.split(",");
int osFd= 0;
int len= 0;
try {
osFd= new Integer(wsArray[0]);
} catch (NumberFormatException e) {
throw new IllegalArgumentException(e.getMessage());
}
try {
len= new Integer(wsArray[1]);
} catch (NumberFormatException e) {
throw new IllegalArgumentException(e.getMessage());
}
//Log.i(TAG, "Read fd " + Integer.toString(osFd) + " for " + len + " bytes.");
fd= new FileDescriptor();
Class<?> c= fd.getClass();
Field f= c.getDeclaredField("descriptor");
f.setAccessible(true);
f.setInt(fd, osFd);
FileInputStream in= new FileInputStream(fd);
FileChannel fc= in.getChannel();
mbb= fc.map(FileChannel.MapMode.READ_ONLY, 0, len);
mbb.order(ByteOrder.LITTLE_ENDIAN);
if (mbb.getInt(PA_MAGIC) != PROP_AREA_MAGIC) {
throw new IllegalArgumentException("Wrong kind of magic " + Integer.toString(mbb.getInt(PA_MAGIC), 16));
}
if (mbb.getInt(PA_VERSION) != PROP_AREA_VERSION) {
throw new IllegalArgumentException("Incorrect version " + Integer.toString(mbb.getInt(PA_VERSION), 16));
}
mMap= mbb;
return(true);
}
public static String get(String key) throws IllegalArgumentException,
SecurityException,
NoSuchFieldException,
IllegalAccessException,
IOException {
if (mMap == null) {
if (!init())
return(null);
}
int index= property_find(key);
//Log.i(TAG, "Found entry at " + Integer.toString(index));
if (index < 0)
return(null);
return(getString(index+PA_INFO_VALUE));
}
private static int property_find(String name) {
int count= mMap.getInt(PA_COUNT);
int tok= -1;
//Log.i(TAG, "Key " + name);
next: while(count-- > 0) {
tok++;
int entry= mMap.getInt(PA_TOC + tok*4);
//Log.i(TAG, "Entry " + tok + ": " + Integer.toString(entry, 16));
if ((entry >> 24) != name.length())
continue;
int index= (entry & 0xFFFFFF);
//Log.i(TAG, "Index " + index);
for (int i=0; i<name.length(); i++) {
//Log.i(TAG, "Cmp(" + entry + ":" + index + ":" + i + "): " + (char)(mbb.get(index+i)) + " -- " + name.charAt(i));
if ((char)(mMap.get(index+i)) != name.charAt(i)) {
continue next;
}
}
// found
return(index);
}
return(-1);
}
private static String getString(int index) {
byte b[]= new byte[PROP_VALUE_MAX];
int i= 0;
do {
b[i]= mMap.get(i+index);
} while (b[i++] != 0);
return(new String(b, 0, i-1));
}
}
Sorry 'bout the terrible indentation. Cut'n'paste isn't my code's best friend, obviously.

[Q] Android Maps draw path problem

I am developing an application which draws the path of the user as he moves and calculates the area .
This is the code i am trying my problem is at the start of recording the path the path is drawn even if the user has not moved and sometimes when even if user is moving the path is not drawn .
RouteOverlay class:
public class RouteOverlay extends Overlay {
private GeoPoint gp1;
private GeoPoint gp2;
private int mode = 1;
public RouteOverlay(GeoPoint paramGeoPoint1, GeoPoint paramGeoPoint2,int paramInt)
{
this.gp1 = paramGeoPoint1;
this.gp2 = paramGeoPoint2;
this.mode = paramInt;
}
public void draw(Canvas paramCanvas, MapView paramMapView,
boolean paramShadow)
{
super.draw(paramCanvas, paramMapView, paramShadow);
Projection projection = paramMapView.getProjection();
Paint mPaint = new Paint();
mPaint.setDither(true);
mPaint.setAntiAlias(true);
mPaint.setColor(Color.RED);
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(3);
mPaint.setAlpha(120);
Point p1 = new Point();
Point p2 = new Point();
Path path = new Path();
projection.toPixels(gp1, p1);
projection.toPixels(gp2, p2);
path.moveTo(p2.x,p2.y);
path.lineTo(p1.x,p1.y);
paramCanvas.drawPath(path, mPaint);
}
MainActivity:
public class MainActivity extends MapActivity {
public final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
coordinates.add(location);
mapView.getController().animateTo(getGeoByLocation(location));
drawRoute(coordinates, mapView);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_area_measurement);
this.mapView = ((MapView) findViewById(R.id.mapview));
this.mapView.setBuiltInZoomControls(false);
this.mapView.getController().setZoom(17);
this.coordinates = new ArrayList<Location>();
}
protected boolean isRouteDisplayed() {
return false;
}
private GeoPoint getGeoByLocation(Location location) {
GeoPoint gp = null;
try {
if (location != null) {
double geoLatitude = location.getLatitude() * 1E6;
double geoLongitude = location.getLongitude() * 1E6;
gp = new GeoPoint((int) geoLatitude, (int) geoLongitude);
}
} catch (Exception e) {
e.printStackTrace();
}
return gp;
}
public String getLocationProvider(LocationManager paramLocationManager) {
try {
Criteria localCriteria = new Criteria();
localCriteria.setAccuracy(1);
localCriteria.setAltitudeRequired(false);
localCriteria.setBearingRequired(false);
localCriteria.setCostAllowed(true);
localCriteria.setPowerRequirement(3);
String str = paramLocationManager.getBestProvider(localCriteria,
true);
return str;
} catch (Exception localException) {
while (true) {
localException.printStackTrace();
}
}
}
private void drawRoute(ArrayList<Location> paramArrayList,MapView paramMapView) {
List<Overlay> overlays = paramMapView.getOverlays();
//Changed for smooth rendering
overlays.clear();
for (int i = 1; i < paramArrayList.size(); i++) {
overlays.add(new RouteOverlay(getGeoByLocation(paramArrayList.get(i - 1)), getGeoByLocation(paramArrayList.get(i)),2));
}
}
public void startRecording() {
this.isMeasuring = true;
lm = (LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(getLocationProvider(lm),500,2,this.locationListener);
/*if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
gpsstatus.setText("Gps Is Enabled");
}else
{ gpsstatus.setText("Gps Is disabled");}*/
}
This probably has to do with the accuracy of the GPS. I didn't really look at your code but maybe you should add some kind of buffer. if (movement>5m){//draw stuff}

[Q] Android camera in portrait but playing in landscape

I have this code below. The problem is i set the orientation of camera to portrait, even preview is portrait. But when i playback that video i see it in landscape mode. Do you guys know why and how i can fix this? Is there a way to rotate VideoView when i playback or to rotate video itself after recording..? I beg you, help me, anywhere i ask nobody knows why and how to fix it...
Here is the code:
Code:
public class BetaRecordActivity extends Activity {
private Preview preview;
private Camera camera;
private MediaRecorder recorder;
private int defaultCameraId;
private int videoCount;
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.beta_record, menu);
return true;
}
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_beta_record);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
initCameraAndPreview();
videoCount = 0;
preview.setOnTouchListener(new View.OnTouchListener() {
[user=439709]@override[/user]
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
releaseCamera();
getThatCamReady();
recorder.start();
videoCount ++;
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
stopRecording();
break;
}
return true;
}
});
}
[user=439709]@override[/user]
protected void onResume() {
super.onResume();
}
[user=439709]@override[/user]
protected void onPause() {
super.onPause();
}
private boolean getThatCamReady() {
camera = getCameraInstance();
setCameraDisplayOrientation(this, defaultCameraId, camera);
camera.unlock();
recorder = new MediaRecorder();
recorder.setCamera(camera);
recorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
recorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
File tempFile = new File(Environment.getExternalStorageDirectory(), "/rec/temp/video_" + String.valueOf(videoCount) + ".mp4");
recorder.setOutputFile(tempFile.getPath());
recorder.setMaxDuration(12500);
recorder.setMaxFileSize(7000000);
recorder.setPreviewDisplay(preview.getHolder().getSurface());
try {
recorder.prepare();
} catch (IllegalStateException e) {
releaseMediaRecorder();
return false;
} catch (IOException e) {
releaseMediaRecorder();
return false;
}
return true;
}
private void stopRecording() {
//timer.pause();
try {
recorder.stop();
} catch(RuntimeException stopException) {
// Handle the cleanup here
//badList.add(videoCount);
//videoCount--;
//RecordActivity.this.timeLeft.setText(String.valueOf(videoCount));
}
releaseMediaRecorder();
}
private void initCameraAndPreview() {
// Find the total number of cameras available
int numberOfCameras = Camera.getNumberOfCameras();
// Find the ID of the default camera
CameraInfo cameraInfo = new CameraInfo();
for (int i = 0; i < numberOfCameras; i++) {
Camera.getCameraInfo(i, cameraInfo);
if (cameraInfo.facing == CameraInfo.CAMERA_FACING_BACK) {
defaultCameraId = i;
}
}
camera = getCameraInstance();
setCameraDisplayOrientation(this, defaultCameraId, camera);
preview = new Preview(this, camera);
FrameLayout myCameraPreview = (FrameLayout)findViewById(R.id.videoview);
myCameraPreview.addView(preview);
}
private void releaseMediaRecorder(){
if (recorder != null) {
recorder.reset();
recorder.release();
recorder = null;
camera.lock();
}
}
private void releaseCamera(){
if (camera != null){
camera.release();
camera = null;
}
}
private Camera getCameraInstance(){
// TODO Auto-generated method stub
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
public static void setCameraDisplayOrientation(Activity activity,
int cameraId, android.hardware.Camera camera) {
android.hardware.Camera.CameraInfo info =
new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(cameraId, info);
int rotation = activity.getWindowManager().getDefaultDisplay()
.getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0: degrees = 0; break;
case Surface.ROTATION_90: degrees = 90; break;
case Surface.ROTATION_180: degrees = 180; break;
case Surface.ROTATION_270: degrees = 270; break;
}
int result;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360; // compensate the mirror
} else { // back-facing
result = (info.orientation - degrees + 360) % 360;
}
camera.setDisplayOrientation(result);
}
}

[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] :How to use list view for Map

Hi,
I am developing an android app in which i am using csv file and displaying column contents as listview its displaying as [a,b,c,d] in single row how to display them in individual row in listview.Please any one help me how to achive this.
This is my csv file reading code using hashcode.
Code:
public static Map<String,ArrayList<String>> parseCsv(InputStreamReader reader, String separator, boolean hasHeader) throws IOException {
Map<String,ArrayList<String> > values = new LinkedHashMap<String,ArrayList<String>>();
List<String> columnNames = new LinkedList<String>();
BufferedReader br = null;
br = new BufferedReader(reader);
String line;
int numLines = 0;
while ((line = br.readLine()) != null) {
//if (StringUtils.isNotBlank(line)) {
//if (!line.startsWith("#")) {
String[] tokens = line.split(separator);
if (tokens != null) {
for (int i = 0; i < tokens.length; ++i) {
if (numLines == 0) {
columnNames.add(hasHeader ? tokens[i] : ("row_"+i));
} else {
ArrayList<String> column = values.get(columnNames.get(i));
if (column == null) {
column = new ArrayList<String>();
}
column.add(tokens[i]);
values.put(columnNames.get(i), column);
}
}
}
++numLines;
}
// }//
// }//
return values;
listview code is:
Code:
oslist.add(values);
ListView list = (ListView) findViewById(R.id.studentnames);
String name="name";
// Add it listview
ListAdapter adapter = new SimpleAdapter(this,
oslist, R.layout.student_list, new String[] { name }, new int[] { R.id.name});
list.setAdapter(adapter);

Categories

Resources