Tuesday, April 16, 2013

[android help] How do I get an Android service to broadcast an intent every few seconds?

How do I get an Android service to broadcast an intent every few seconds? - Stack Overflow








Tell me more ×

Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

















If I've created a service, how do I get it to broadcast an intent every X seconds? I remember seeing a snippet of code along the lines



startThreadDelayed( new Thread() {
public void run() {
doStuff();
sendBroadcast(messageIntent);
startThreadDelayed(this, 1000);
}
}, 1000);


Unfortunatelly I'm not sure of either the class name, or the exact method name, for whatever is looping. Just a name would point me in the right direction of searching.


























you can use Handler.postDelayed. Here is the documentation.


For Example



Handler h = new Handler();
YourClass yourRunnable = new YourClass();
h.postDelayed(youRunnable,1000);


public class YourClass implements Runnable{
public void run(){
doStuff();
sendBroadcast(messageIntent);
if(running)
h.postDelayed(youRunnable,1000);
}


here running is a flag better keep it as volatile boolean. So that by changing it's value you can stop the repeatition.


























You may consider using AlarmManager. By using it you can trigger any Intent one-time or recurring with any schedule.


For example:



Intent i = new Intent(this, YourReceiver.class);
PendingIntent broadcast = PendingIntent.getBroadcast(this, 0, i, 0);

long first = System.currentTimeInMillis(); // now
long interval = 5 * 1000; // every 5 seconds
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC, first, interval, broadcast);



















default







.

stackoverflow.comm

[android help] Unexpected crash using jni in monodroid project


I've been trying to import a simple hello world NDK project into a monodroid project using Xamarin Studio.


The NDK part of the project compiles and builds fine, I can invoke the native methods but when I try to access the JNIEnv the app crashes with a SIGSEGV, see below for console output and relevant code snips.



Very basic console logging
Starting method
Accessing env
Stacktrace:

at <0xffffffff>
at (wrapper managed-to-native) BasicNDK.Activity1.LogNdk (string)
at BasicNDK.Activity1.b__0 (object,System.EventArgs) [0x00023] in c:\Users\cbramley\Documents\Visual Studio 2012\Projects\AndroidApplication1\BasicNDK\MainActivity.cs:56
at Android.Views.View/IOnClickListenerImplementor.OnClick (Android.Views.View) [0x0000c] in /Users/builder/data/lanes/monodroid-mlion-master/bf2b736d/source/monodroid/src/Mono.Android/platforms/android-10/src/generated/Android.Views.View.cs:643
at Android.Views.View/IOnClickListenerInvoker.n_OnClick_Landroid_view_View_ (intptr,intptr,intptr) [0x00011] in /Users/builder/data/lanes/monodroid-mlion-master/bf2b736d/source/monodroid/src/Mono.Android/platforms/android-10/src/generated/Android.Views.View.cs:614
at (wrapper dynamic-method) object.6ea2e501-d56c-455b-9c13-849da747461e (intptr,intptr,intptr)
at (wrapper native-to-managed) object.6ea2e501-d56c-455b-9c13-849da747461e (intptr,intptr,intptr)

=================================================================
Got a SIGSEGV while executing native code. This usually indicates
a fatal error in the mono runtime or one of the native libraries
used by your application.
=================================================================


The monodroid activity code:



// snipped rest of activity
[DllImport ("ndksample")]
static extern void LogNdk ( string w );

[DllImport ("ndksample")]
static extern void LogNdkDefaultMessage ();

protected override void OnCreate ( Bundle bundle )
{
base.OnCreate ( bundle );
SetContentView ( Resource.Layout.Main );

Button button = FindViewById

Finally the NDK implementation:



#include
#include
#include

#define DEBUG_TAG "NDK_AndroidNDK1SampleActivity"

void LogNdk(JNIEnv * env, jobject this, jstring logThis)
{
__android_log_print(ANDROID_LOG_DEBUG, DEBUG_TAG, "Starting method");
jboolean isCopy;
__android_log_print(ANDROID_LOG_DEBUG, DEBUG_TAG, "Accessing env");
const char * szLogThis = (*env)->GetStringUTFChars(env, logThis, &isCopy);
__android_log_print(ANDROID_LOG_DEBUG, DEBUG_TAG, "NDK:LC: [%s]", szLogThis);
(*env)->ReleaseStringUTFChars(env, logThis, szLogThis);
__android_log_print(ANDROID_LOG_DEBUG, DEBUG_TAG, "Finished");
}

void LogNdkDefaultMessage(JNIEnv * env, jobject this)
{
__android_log_print(ANDROID_LOG_DEBUG, DEBUG_TAG, "Very basic console logging");
}


I've tracked the problem down to a crash on this line const char * szLogThis = (*env)->GetStringUTFChars(env, logThis, &isCopy); but I don't understand what's causing it, can anyone help explain it to me please? Or better yet tell me how to fix it :)



.

stackoverflow.comm

[android help] Punch a hole into a texture in OpenGL ES 2.0 (Android)

Punch a hole into a texture in OpenGL ES 2.0 (Android) - Stack Overflow








Tell me more ×

Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

















I'm drawing a background texture to the screen, and then a foreground texture, now i wan't to punch a hole into the foreground texture where the user touches the screen. The result should be the foreground texture with a hole, and through the hole you see the background texture. How do i achieve this via OpenGL ES 2.0. I know i can do it with canvas and PorterDuff, but this method is too slow for me.


























Did you solve the problem? I'm in the same situation now. I tried to draw 3 kind of mesh in a view. One is a simple plane which is at the bottom. Second is also a simple plane which is at the middle layer. Last one is a circle primitive which is for punching a hole.


When I drew a circle, all plane was punched even though the bottom plane should be not punched. I just tried to test 2 ways. pseudo code. 1st way. circle.enableBlend(true); circle.blendFunc(GL_ZERO, GL_ZERO);


2nd way. circle.enableBlend(false);




















default







.

stackoverflow.comm

[android help] Android ListView doesn't cooperate


I've been studying Android ListViews recently and I'm having some issues. I looked at a few tutorials and got the most basic ListViews working just fine. But now I would like to make a ListView that displays a series of objects. I thought I was doing everything correct. My code does not produce any errors but the List I wish to create does not display at all. Obviously, I'm not sure why.


The Purpose of this application is to compile a list of weather stations and airports and display information (ex. names, ID#, coordinates, etc) - all of which is parsed from an XML document and contained in an Arraylist(Built by a separate class with proper constructors/getters/setters). Basically I get a list of stations then - then from that list - a list of station names set to an Adapter. My ListView should display only the names of each station but to no avail.


I've tested my Parser and My Arrays. It all works, just nothing displays. According to all the tutorials my logic should be correct down to my Adapter. Does anyone have any suggestions? I feel like I'm exhausting all solutions. My code is posted below:



public class MainActivity extends Activity {

//local variables
String station_id;
String state;
String station_name;
double latitude;
double longitude;
String html_url;

//ArrayList stationList = new ArrayList();
public ArrayList stationList = new ArrayList();

private ListView stationName;
private ArrayAdapter arrayAdapter;



//Method for DOM Parser
public void readXML(){

try {

//new xml file and Read
File file1 = new File("src/fl_wx_index3.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file1);
doc.getDocumentElement().normalize();

NodeList nodeList = doc.getElementsByTagName("station");

for (int i = 0; i < nodeList.getLength(); i++) {

Node node = nodeList.item(i);

if(node.getNodeType() == Node.ELEMENT_NODE){

final Element first = (Element) node;

station_id = first.getElementsByTagName("station_id").item(0).getTextContent();
state = first.getElementsByTagName("state").item(0).getTextContent();
station_name = first.getElementsByTagName("station_name").item(0).getTextContent();
latitude = Double.parseDouble(first.getElementsByTagName("latitude").item(0).getTextContent());
longitude = Double.parseDouble(first.getElementsByTagName("longitude").item(0).getTextContent());
html_url = first.getElementsByTagName("html_url").item(0).getTextContent();

//iterate thru list, returning names of each airport
stationList.add(new Station(station_id, state, station_name, latitude, longitude, html_url));

}

}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}

}



@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize the UI components
stationName = (ListView) findViewById(R.id.listView1);

//object for method call to read XML document
MainActivity activity1 = new MainActivity();
activity1.readXML();

//List to contain Weather station Names
final ArrayList nameList = new ArrayList();

for (int i = 0; i < stationList.size(); ++i) {
nameList.add(stationList.get(i).getStationName());
}

arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, nameList);

// By using setAdapter method, you plugged the ListView with adapter
stationName.setAdapter(arrayAdapter);

}

@Override
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;
}


}


Here is a sample of XML:





NOAA's National Weather Service
http://weather.gov/

http://weather.gov/images/xml_logo.gif
NOAA's National Weather Service
http://weather.gov

08:00 EST
1140


NFNA
FJ
Nausori
-18.05
178.567
http://weather.noaa.gov/weather/current/NFNA.html
http://weather.gov/xml/current_obs/NFNA.rss
http://weather.gov/xml/current_obs/NFNA.xml



KCEW
FL
Crestview, Sikes Airport
30.79
-86.52
http://weather.noaa.gov/weather/current/KCEW.html
http://weather.gov/xml/current_obs/KCEW.rss
http://weather.gov/xml/current_obs/KCEW.xml



Activity main XML:



xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />

android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_marginTop="115dp"
android:layout_toRightOf="@+id/textView1" >



.

stackoverflow.comm

[android help] SKU not available for in app purchase during testing

android - SKU not available for in app purchase during testing - Stack Overflow








Tell me more ×

Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

















I am adding in-app-billing to one of my existing apps. To test this I created a draft app in google play, uploaded the new version of the apk with in-app-billing and added a product. I activated this product but I did not publish this new test app.


But while testing, on querying for the newly created SKU, the code can't find it. Will I have to publish my app for this to work? Am I doing something wrong here?


EDIT: I am using IABv3.





























I found the problem. I was using the TrivialDrive sample. I was under the impression that the code will automatically find and load all the SKUs. But after going through the documentation once again I found that I needed the pass the SKUs as a parameter.



ArrayList skuList = new ArrayList();
skuList.add(Product.SKU);

Log.d(TAG, "Setup successful. Querying inventory.");
//mHelper.queryInventoryAsync(mGotInventoryListener);
mHelper.queryInventoryAsync(true, skuList, mGotInventoryListener);



















default







.

stackoverflow.comm

[android help] Android horizontal scrolling container like Gallery


First of all, sorry for my bad english. Hope to understand about that.


Please check below url what I want to do. https://dl.dropboxusercontent.com/u/48372563/Masterpieces/device-2013-04-17-003424.png


I want to make horizontal scroll viewer like Gallery. But Gallery is deprecated now. So I am going to find other scrollable container such as HorizontalScrollView or HorizontalListView instead of Gallery.


Scrollable container should have property for center-locking, velocity and every child item's width can be able to adjusted dynamically.


I think we can use HorizontalListView or HorizontalScrollView, ViewPager. But there are issues with them. HorizontalListView or HorizontalScrollView doesn't have "center-locked" function and ViewPager doesn't have veolocity function. I researched VeolocityViewPager also, but there is no touch event handler for child items.


Best example of this is pulse news reader :- https://market.android.com/details?id=com.alphonso.pulse


Anyone can help me now?


Thanks :)



.

stackoverflow.comm

[General] thick I know!


Are you saying that you're taking pictures with your tablet, and would like to save those pictures by default to the SD card? That should be under the Camera app's Settings. Open the Camera app, hit the Menu or Settings button (I'm not familiar with Samsung's Camera app, but it probably looks like a gear), and scroll through that menu until you find a selection for Storage Location. You should be able to select between Internal Storage and SD Card--pick the latter.

The folder that it saves to on the card is usually /DCIM/Camera/



.

forum.xda-developers.com

[General] Looking for a way to move mass mp3 files from one android to another via Bluetooth....


I know I can multi select and zip them and send via Bluetooth, but once you try to extract the songs from the zip file, it wants to name each file the same as you named the zip file.

I would like to be able to move many songs from one phone to another with Bluetooth. Any ideas??

Sent from my ADR6425LVW using Tapatalk 2



.

forum.xda-developers.com

[android help] Android Toast with multi-colors


Try doing this i hope this is what you realyy want



richTextView = (TextView)findViewById(R.id.rich_text);

// this is the text we'll be operating on
SpannableString text = new SpannableString("hello how are you");

// make "hello" to (characters 0 to 5) red color
text.setSpan(new ForegroundColorSpan(Color.RED), 0, 5, 0);

richTextView.setText(text, BufferType.SPANNABLE);


And if you want it to show it as toast try this instead of setText use it like this



Toast.makeText(context, text, Toast.LENGTH_LONG).show();


enter image description here



.

stackoverflow.comm

[android help] Need to access AsyncTask value in Main Class


I am facing an issue in Async task, can anyone please suggest me any solution.
I have downloaded this example from this link :
Source


My Current Structure is


  • Main Class extends MyTask and implements AsyncTaskCompleteListener interface.

  • AsyncTaskCompleteListener is an Interface contains the onTaskComplete Method .

  • MyTask extends Async Task and onPostExcute contains CallBackMethod which will return the result-set got from the doInBackground.

  • Http Class(Utils) contains the Http connection and returns the Result-set to AsyncTaskComleteListner from PostExecute.

I am trying to get my result-set Value in the main class from the interface method to perform my further operation.
I tried to get the value from static variables, static method but non of them worked, and also tried with creating a new class object to send and receive the result but every time it gives me NullPointerException . Because the statement written after the AsyncTask gets executes before getting the result.


I have also tried to get the Status of asyncTask from its method getStaus(), but it returns only Running and dose not notify when the task is completed or finished.


Here is the code sample:


Main Class Code :



package com.example.androidasynctask;


public class MainActivity extends Activity implements AsyncTaskCompleteListener {

public static String[] asyncResult;
String res[] = null;



@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

public void btnclick(View view) {
/*MyTask asyncTask = new MyTask(this);
String [] asyncTaskResult = asyncTask.execute("fetchCategory.php","1%Id%1");*/

//AsyncTask asyncTaskRes = new MyTask(this).execute("fetchCategory.php","1%Id%1");
//new MyTask(this).execute("fetchCategory.php","1%Id%1");
MyTask asyncTask = (MyTask) new MyTask(this).execute("fetchCategory.php","1%Id%1");

if(asyncTask.getStatus().equals(AsyncTask.Status.FINISHED) || asyncTask.getStatus().equals(AsyncTask.Status.PENDING)) {
asyncTask.execute();
}
else {

Log.v("In Else","Get Value");
}



}

@Override
public void onTaskComplete(String[] result) {
Log.v("IN ON TASK COMPLETE","VALUE = "+result[1]);


}



/*@Override
public void onTaskComplete(String result) {
System.out.println("calling onTaskComplete SIMPLE....");
System.out.println("result :: "+ result);
}*/

public static class GetAsyncResult
{
static String[] returnValues;


public GetAsyncResult()
{}
public GetAsyncResult(String[] res)
{

returnValues = res;
Log.v("getResultSetValues","returnValues"+returnValues[1]);
}


public void getResultSetValues()
{
Log.v("getResultSetValues","returnValues"+returnValues[1]);


}

}

}


Async Task Code :



public class MyTask extends AsyncTask {

private Activity activity;
private ProgressDialog dialog;
private AsyncTaskCompleteListener callback;
public String[] asyncResultSetValue = null;
public MyTask(Activity act) {
Log.v("MY TASK","ACTIVITY"+act);
this.activity = act;
this.callback = (AsyncTaskCompleteListener)act;
}

@Override
protected void onPreExecute() {
super.onPreExecute();

Log.v("MY TASK","in ON PRE EXECUTE");
dialog = new ProgressDialog(activity);
dialog.setMessage("Loading...");
dialog.show();
}

@Override
protected String[] doInBackground(String... params) {
Log.v("MY TASK","DO IN BACKGROUND");
Log.v("PARAMS"," params[0] = "+params[0]+ "| params[1]"+params[1]);
asyncResultSetValue = Utils.process_query(params[0],params[1]);
return asyncResultSetValue;
}

@Override
protected void onPostExecute(String[] result) {
super.onPostExecute(result);
Log.v("MY TASK","in ON POST EXECUTE");
if (null != dialog && dialog.isShowing()) {
dialog.dismiss();
}
callback.onTaskComplete(result);
}

}


HTTP CLASS CODE :



public class Utils {

static String result = null;
String endResult;
static java.io.InputStream is = null;
static StringBuilder sb=null;
static String delimiter = "\\|";
static String delimiter1 = "\\%";
static String[] temp = null;
static String[] temp1 = null;
static ArrayList nameValuePairs;
static Context context;
static ProgressDialog mDialog;
static HttpResponse response;
static String[] resultset_value = null;
//static String url = "http://fortuneworkinprogress.in/News_App/"; //Global URL
static String url = "http://10.0.2.2/News_App/"; //Global URL
static String query_type,parameter;

/*************** PROCESS QUERY START ***************/
public static String[] process_query(String str_url, String parameter) {
// String strval = select_parameter;
String ret_val[] = null;
String get_sel_val[] = null;
int loopcount =0;
url = url+str_url; //!!!! ######### CONCATINATING AND CREATING FULL URL ######## !!!!!!//
Log.v("PROCESS QUERY PARAMETER","URL = "+url+" | PARAMTER = "+parameter);
nameValuePairs = new ArrayList();

//Log.i("STR VAL",""+strval); //To Check which values are recieved
try
{
String strval = parameter;
get_sel_val=strval.split(delimiter1);

for(int i =0; i < get_sel_val.length ; i++)
{

loopcount = Integer.parseInt(get_sel_val[0]); // First Delimeted Value which tells the number of count
Log.i("Loopcount","cnt = "+loopcount);

}

for(int j=1;j<=(loopcount*2);j=j+2) //For Loop for making Name Values Pares Dynamic
{
nameValuePairs.add(new BasicNameValuePair(get_sel_val[j],get_sel_val[j+1]));
//Log.i("J = ["+j+"]","pairvalue1 = "+get_sel_val[j]+"pairvalue2 ="+get_sel_val[j+1]);
}
}
catch(Exception e)
{
Log.w("Exception in the getting value","Exp = "+e);
}

//nameValuePairs.add(new BasicNameValuePair("id","1"));

try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
Log.v("CONNECT URL ","Final url "+url);
Log.w("CONNECTION STATUS ",httppost.toString());
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.w("PAERSE VALUE ",nameValuePairs.toString());
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.w("1", "Connection establised succesfuly");
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection"+e.toString());
}

try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
Log.v("SB VALUE = ","sb = "+sb.toString());
String line="0";
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result=sb.toString();

// Toast.makeText(getBaseContext(), result ,Toast.LENGTH_LONG).show();

Log.w("result", result);
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
Toast.makeText(null, "error converting response to string" ,Toast.LENGTH_LONG).show();
}

String[] temp = null;
String[] tempResult = null;

if(result!=null)
{
tempResult = result.split(delimiter); //Split the entire return string into "rows"
for(int i =0; i < tempResult.length-1 ; i++)
{
temp = null;
temp = tempResult[i].split(delimiter1); //Find columns for each row
ret_val = temp;
resultset_value=ret_val;
}
}
else
{
Toast.makeText(null, "Cannot Find Routes" ,Toast.LENGTH_LONG).show();
}

Log.v("BEFORE RETUNR = ","ret_val = "+ret_val.toString());
return ret_val; //Returning the result value array
}


/*************** PROCESS QUERY ENDS ***************/

public static boolean isNetworkAvailable(Activity activity)
{
ConnectivityManager connectivity = (ConnectivityManager) activity
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null)
{
return false;
}
else
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
{
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
}
}
return false;
}

}


Thanks in advance.



.

stackoverflow.comm

[android help] How to provide progressive audio streaming with progressiv download in Box Api


What i want to do in my project is to play audio songs which are inside my Box account for that i am using box api . As i know we can not provide direct audio streaming for audio files in Box api for that i am trying to implement progressive download and playing audio file from sd card . i know i can play song inside on complete method of download but this is taking more time to download and than playing file . for that what i did i wrote my code for playing audio inside on progress method of downloading file but this method is getting called so many times because of that same song is playing multiple time at a time.


So is there any way to write code for progressive audio playing in Box api .if yes where should i write that ?



* Download a file and put it into the SD card. In your app, you can put the file wherever you have access to.
*/
final Box box = Box.getInstance(Constants.API_KEY);
String PATH = Environment.getExternalStorageDirectory() + "/chaseyourmusic"+folderpath;
File file = new File(PATH);
file.mkdirs();
final java.io.File destinationFile = new java.io.File(PATH + "/"
+ URLEncoder.encode(items[position].name));
/* final java.io.File destinationFile = new java.io.File(Environment.getExternalStorageDirectory() + "/"
+ URLEncoder.encode(items[position].name));*/

final ProgressDialog downloadDialog = new ProgressDialog(Browse.this);
downloadDialog.setMessage("Downloading " + items[position].name);
downloadDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
downloadDialog.setMax((int) items[position].file.getSize());
downloadDialog.setCancelable(true);
downloadDialog.show();

Toast.makeText(getApplicationContext(), "Click BACK to cancel the download.", Toast.LENGTH_SHORT).show();

final Cancelable cancelable = box.download(authToken, items[position].id, destinationFile, null, new FileDownloadListener() {

@Override
public void onComplete(final String status) {
downloadDialog.dismiss();
if (status.equals(FileDownloadListener.STATUS_DOWNLOAD_OK)) {
//Able to play audio here from sd card but this is playing after completion of download only which is taking more time .


}
else if (status.equals(FileDownloadListener.STATUS_DOWNLOAD_CANCELLED)) {
Toast.makeText(getApplicationContext(), "Download canceled.", Toast.LENGTH_LONG).show();
}
}

@Override
public void onIOException(final IOException e) {
e.printStackTrace();
downloadDialog.dismiss();
Toast.makeText(getApplicationContext(), "Download failed " + e.getMessage(), Toast.LENGTH_LONG).show();
}

@Override
public void onProgress(final long bytesDownloaded) {
downloadDialog.setProgress((int) bytesDownloaded);
//Want to write code here but this method is getting called multiple times which is creating problem in playing audio files from sd card .


}
});
downloadDialog.setOnCancelListener(new OnCancelListener() {

@Override
public void onCancel(DialogInterface dialog) {
cancelable.cancel();
}
});


Thanks



.

stackoverflow.comm

[android help] How to call a function in TabActivity from a child activity?


I want to update the title of the tab according to the content of my child activity.


However, when I call:



TabActivity parent = (TabActivity) getParent();
TabHost parentHost = (TabHost) parent.getTabHost().findViewById(android.R.id.tabhost);


in the child, the program crashes.


Anyone can help me discover the problem and solve it?


My TabActivity setup:



public class Tab extends TabActivity {
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.tab);

final TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost);

View newTab = (View) LayoutInflater.from(this).inflate(R.layout.tabmini, null);
TextView text0 = (TextView) newTab.findViewById(R.id.tab_label);
text0.setText("new tab");

tabHost.setup(this.getLocalActivityManager());
tabHost.setCurrentTab(1);

tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator(newTab).setContent(new Intent(this, BrowserActivity.class)));

}

public void addTab(TabHost tabHost, String startPage){
//...Add a new Tab
}

}


.

stackoverflow.comm

[android help] How to set scroll position for long PreferenceScreen


I know this is an old one, so this answer is just for reference.


To auto-select a given screen, all you have to do is setPreferenceScreen() (this is for a pre-Honeycomb non-Fragment PreferenceActivity).


Once you're on the correct PreferenceScreen, you can indeed use getListView().smoothScrollToPosition(position) (but this is a Froyo+ method), or you can use getListView.setSelection(position).


But how to get the position?


First, watch out for the trap: PreferenceActivity.getListAdapter() does not return the actual ListAdapter, but a local instance variable which is disconcertingly not in sync with PreferenceActivity.getListView().getAdapter() (and usually null).


Second, trying to use Preference.getOrder() returns the order of the Preference object within its parent, which is what you want to use for the position only if you're not using PreferenceCategories since what you need is its order within the PreferenceScreen.


If you are using PreferenceCategories, you need to iterate over the items in the adapter (for (int i = 0; i < adapter.getCount(); i++)until you find the right one, and use its position.


Another corner of the Android SDK that is in dire need of some attention…



.

stackoverflow.comm

[android help] How to show devider in listview when there is only single item present

android - How to show devider in listview when there is only single item present - Stack Overflow







Tell me more ×

Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

















I have a listview but it only shows devider between two items , i have a case where i have to show devider when there is only single item present or only few items are present that do not fill the whole page , In such case no devider appears on last item that & looks weird. Footerview can not help as deviders images are indiapendant from phone to phone . Can any one help ?
















Know someone who can answer? Share a link to this question via email, Google+, Twitter, or Facebook.










default






.

stackoverflow.comm

[android help] Sending data from android app to server(database) [closed]

java - Sending data from android app to server(database) - Stack Overflow







Tell me more ×

Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

















I am creating a shopping mall application for Android, in which I need to communicate with the remote server(database). I am able to retrieve data from the server using a JSON parser, but I don't know how to send data from the app back to the server(database). Can anyone help me with the solution, as I'm new to Android development.



















It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, see the FAQ.















You really should try something before asking.


If you are retrieving data in JSON format, you should try to send it in JSON too. One way is to use some HTTP client to connect to web server.


Another question worth reading: Send data from android to server via JSON

















default






.

stackoverflow.comm

[android help] ClassCastException error, dont know why it occurs

java - ClassCastException error, dont know why it occurs - Stack Overflow







Tell me more ×

Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

















I m working with BaseAdapter class and i get an ClassCastException error in getView method when i try to cast my viewHolder class.


Here is my code:



public View getView(int position, View convertView, ViewGroup parent){
// TODO Auto-generated method stub
NoteItem noteItem = list.get(position);
TextView tv;
LinearLayout ll;
if(convertView == null){
convertView = inflater.inflate(R.layout.dialog_listitem_note, null);
ll = (LinearLayout) convertView.findViewById(R.id.llNote);
tv = (TextView) convertView.findViewById(R.id.tvNoteItem);
convertView.setTag(new NoteItemViewHolder(tv, ll));
ll.setOnClickListener(new OnClickListener(){...});
}else{
NoteItemViewHolder viewHolder = (NoteItemViewHolder) convertView.getTag(); //ClassCastException error here
ll = viewHolder.getLl();
tv = viewHolder.getName();
}
tv.setText(noteItem.getName());
ll.setTag(noteItem);
...
return convertView;
}

private class NoteItemViewHolder{

TextView name;
LinearLayout ll;

public NoteItemViewHolder(TextView name, LinearLayout ll){
this.name = name;
this.ll = ll;
}

public TextView getName(){
return name;
}

public LinearLayout getLl(){
return ll;
}
}


Dont get why this error occurs, please help.


























getView method should Like below and Also Check Your Control Like LinearLayout is bind with R.id.yourLinearID



public View getView(int position, View view, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
if(view == null)
{
view = inflater.inflate(R.layout.checkin_item, null);
holder = new ViewHolder();

holder.iconImage = (ImageView)view.findViewById(R.id.chkin_item_iv);
holder.placeName = (TextView)view.findViewById(R.id.chkin_item_tv_name);
holder.placeAddress = (TextView)view.findViewById(R.id.chkin_item_tv_address);
holder.placeKm = (TextView)view.findViewById(R.id.chkin_item_tv_0);

view.setTag(holder);
}
else
{
holder = (ViewHolder)view.getTag();
}

try

if(googleSetGetArray.getGoogleSetGets().get(position).getName().length() != 0)
{
holder.placeName.setText(googleSetGetArray.getGoogleSetGets().get(position).getName());
}
else
{
holder.placeName.setText(mContext.getString(R.string.mfitem_lbl_namenotpresent));
}
if(googleSetGetArray.getGoogleSetGets().get(position).getVicinity() != null && googleSetGetArray.getGoogleSetGets().get(position).getVicinity().length() != 0)
{
holder.placeAddress.setText(googleSetGetArray.getGoogleSetGets().get(position).getVicinity());
}
else
{
holder.placeAddress.setText(mContext.getString(R.string.mfitem_lbl_addressnotpresent));
}
if(googleSetGetArray.getGoogleSetGets().get(position).getDistance() != 0.0f)
{
holder.placeKm.setText(Float.toString(googleSetGetArray.getGoogleSetGets().get(position).getDistance()));
}
else
{
holder.placeKm.setText(Float.toString(0.0f));
}
}catch(Exception ex)
{
ex.printStackTrace();
}


imageLoader.DisplayImage(data[position], holder.iconImage);
return view;
}

class ViewHolder
{
ImageView iconImage;
TextView placeName;
TextView placeAddress;
TextView placeKm;

}






















lang-java






.

stackoverflow.comm

[General] N7 now won't go online?


Hi.
New to this.
I've had a Nexus 7 for a few weeks and all seemed ok.
But now it won't go online - it used to.
It does the Google Search thing, but anything clicked on the eventual list only takes me to a blank page.
Do I need to factory reset?
Or is there something else?
(utube items if clicked show up immediately by the way) ????
Puzz



.

forum.xda-developers.com

[android help] xmlpullparser exception while trying to consume a method

android - xmlpullparser exception while trying to consume a method - Stack Overflow







Tell me more ×

Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

















i am trying to consume webservice method using ksaop2.


here is the code



try {

SOAP_ACTION = NAMESPACE + METHOD;

SoapObject request = new SoapObject(NAMESPACE, METHOD);

SoapSerializationEnvelope res = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
res.dotNet = true;
res.setOutputSoapObject(request);

HttpTransportSE call = new HttpTransportSE(url);

SoapPrimitive result;
call.call(SOAP_ACTION, res);
result = (SoapPrimitive) res.getResponse();

ParseLocations Objparsecities = new ParseLocations(
new ByteArrayInputStream(result.toString()
.getBytes("UTF-8")));
lstresponse = Objparsecities.parse();

System.out.println(lstresponse);

} catch (SoapFault e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


it works fine on emulator but when i try to run on my device i am getting the following error



04-16 15:54:11.761: W/System.err(3982): org.xmlpull.v1.XmlPullParserException: unexpected type (position:END_DOCUMENT null@1:0 in java.io.InputStreamReader@405f2fe8)
04-16 15:54:11.761: W/System.err(3982): at org.kxml2.io.KXmlParser.exception(KXmlParser.java:273)
04-16 15:54:11.761: W/System.err(3982): at org.kxml2.io.KXmlParser.nextTag(KXmlParser.java:1413)
04-16 15:54:11.761: W/System.err(3982): at org.ksoap2.SoapEnvelope.parse(SoapEnvelope.java:126)
04-16 15:54:11.761: W/System.err(3982): at org.ksoap2.transport.Transport.parseResponse(Transport.java:63)
04-16 15:54:11.761: W/System.err(3982): at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:100)
04-16 15:54:11.761: W/System.err(3982): at com.netserv.Pungry.LocationbyCities.SendRequesttoServer(LocationbyCities.java:249)
04-16 15:54:11.761: W/System.err(3982): at com.netserv.Pungry.LocationbyCities$CityData.doInBackground(LocationbyCities.java:216)
04-16 15:54:11.761: W/System.err(3982): at com.netserv.Pungry.LocationbyCities$CityData.doInBackground(LocationbyCities.java:1)
04-16 15:54:11.761: W/System.err(3982): at android.os.AsyncTask$2.call(AsyncTask.java:185)
04-16 15:54:11.761: W/System.err(3982): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
04-16 15:54:11.761: W/System.err(3982): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
04-16 15:54:11.761: W/System.err(3982): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
04-16 15:54:11.761: W/System.err(3982): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
04-16 15:54:11.761: W/System.err(3982): at java.lang.Thread.run(Thread.java:1027)
04-16 15:54:11.771: W/System.err(3982): java.lang.NullPointerException
04-16 15:54:11.771: W/System.err(3982): at com.netserv.Pungry.LocationbyCities$CityData.onPostExecute(LocationbyCities.java:202)
04-16 15:54:11.771: W/System.err(3982): at com.netserv.Pungry.LocationbyCities$CityData.onPostExecute(LocationbyCities.java:1)
04-16 15:54:11.771: W/System.err(3982): at android.os.AsyncTask.finish(AsyncTask.java:417)
04-16 15:54:11.771: W/System.err(3982): at android.os.AsyncTask.access$300(AsyncTask.java:127)
04-16 15:54:11.771: W/System.err(3982): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
04-16 15:54:11.771: W/System.err(3982): at android.os.Handler.dispatchMessage(Handler.java:99)
04-16 15:54:11.771: W/System.err(3982): at android.os.Looper.loop(Looper.java:150)
04-16 15:54:11.771: W/System.err(3982): at android.app.ActivityThread.main(ActivityThread.java:4263)
04-16 15:54:11.771: W/System.err(3982): at java.lang.reflect.Method.invokeNative(Native Method)
04-16 15:54:11.771: W/System.err(3982): at java.lang.reflect.Method.invoke(Method.java:507)
04-16 15:54:11.771: W/System.err(3982): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
04-16 15:54:11.771: W/System.err(3982): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
04-16 15:54:11.781: W/System.err(3982): at dalvik.system.NativeStart.main(Native Method)


Can i know what is the mistake?


Thanks:)
















Know someone who can answer? Share a link to this question via email, Google+, Twitter, or Facebook.










default






.

stackoverflow.comm

[android help] Html parsing text from TD Tag

java - Html parsing text from TD Tag - Stack Overflow







Tell me more ×

Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

















I have my Html data











Archive Url
http://www.toradio.com/prgramdetails/20130413_vali_mm.mp3



I want to get mp3 url(http://www.toradio.com/prgramdetails/20130413_vali_mm.mp3) from above html text


I'm following this link,Is it Correct or any better way to parse this text Could any one help?



























just write



link























Check out JSoup. It's a nice HTML Parser for JAVA.




















lang-java






.

stackoverflow.comm

Google Voice on T-Mobile? [General]

Google Voice on T-Mobile? So I recently switched from a GNex on Verizon to a Moto X DE on T-Mobile. I had always used Google Voice for my v...