[Q] [Help] Activity flow - General Questions and Answers

Hello, I am trying to create a simple REST client in android, i have created the client that makes the connections and the service intent. I can call it from the main activity but i have a problem getting the result from the service intent to the activity. How can i achive this? I am kind of confused on how to handle this...
Code:
@Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
final String action = intent.getAction();
if (ACTION_AUTH.equals(action)) {
final String username = intent.getStringExtra(EXTRA_PARAM_USERNAME);
final String password = intent.getStringExtra(EXTRA_PARAM_PASSWORD);
boolean authenticated = handleActionAuth(username, password);
Log.d(TAG, "Result: "+authenticated);
/*** What can i call here to notify the activity??? ***/
} else if (ACTION_BAZ.equals(action)) {
}
}
}
Thanks

Related

[Q][DEV]Android Development Maps Question

I'm trying to develop (for the liveview) using an SDK and need to get a bitmap of Google Maps.
Code:
//Map Section
public class myMap extends MapActivity {
MapView mapView;
Bitmap bitmap;
boolean created = false;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
createMap();
}
public void createMap()
{
// build map and mark point
mapView = new MapView(this, "keykeykeykeykeykey");
mapView.setBuiltInZoomControls(false);
GeoPoint point = new GeoPoint(52242730,-884211);
mapView.getController().animateTo(point);
mapView.preLoad();
// copy MapView to canvas
bitmap = Bitmap.createBitmap(400, 800, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
mapView.draw(canvas);
PluginUtils.sendTextBitmap(mLiveViewAdapter, mPluginId, "Loading Map...", 128, 12);
created = true;
}
public void displayMap()
{
if (created == false)
{
createMap();
}
//Display map on device
Bitmap mybit = Bitmap.createBitmap(128, 128, Bitmap.Config.ARGB_8888);
for(int i = 0; i < 128; i++)
{
for(int j = 0; j < 128; j++)
{
mybit.setPixel(i, j, bitmap.getPixel(i, j));
}
}
//white pixel for debugging
mybit.setPixel(64, 64, Color.WHITE);
}
@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
Is what I've got so far, the code in createMap() was in onCreate() but It didn't seem to be called.
Now it just force closes.
Anyone know how to help? Is there a better place to ask development questions?
Thanks.
-=Edit=-
Oh, and here's the routine calling the map thing, every couple of seconds.
Code:
private class Timer implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
myMap theMap = new myMap();
theMap.displayMap();
}
}
Okay, looks like you cant use google street map like this.
Anyone looking for similar solution, I used open street map and downloaded 'slipery tiles' png's. They provide java routines for finding the tile url from lat/lon.
http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames

[Q] Problem developing app for Android

Hi All,
I am a not experienced developer. All I want to do is make a small app to track information of football on TV. I want to do it through a small DB however I've been struggling a lot with an error I've been trying to discover in the last two weeks but I have not been able.
I have teh following code in the class I create the DB
public class DBAdapter {
public static final String KEY_ROWID = "_id";
public static final String KEY_GDATE = "gdate";
public static final String KEY_GTIME = "gtime";
public static final String KEY_GGAME = "ggame";
public static final String KEY_GCOMPETITION = "gcompetition";
public static final String KEY_GCHANNEL = "gchannel";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "FonTV";
private static final String DATABASE_TABLE = "games";
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE =
"create table games (_id integer primary key autoincrement, "
+ "gdate text not null, gtime text not null, ggame text not null" +
"gcompetition text not null, gchannel text not null);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db)
{
try {
db.execSQL(DATABASE_CREATE);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
//---insert a contact into the database---
public long insertContact(String gdate, String gtime, String ggame, String gcompetition, String gchannel )
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_GDATE, gdate);
initialValues.put(KEY_GTIME, gtime);
initialValues.put(KEY_GGAME, ggame);
initialValues.put(KEY_GCOMPETITION, gcompetition);
initialValues.put(KEY_GCHANNEL, gchannel);
return db.insert(DATABASE_TABLE, null, initialValues);
}
}
And the main class where I try to insert data has this:
public class ResultsDBActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DBAdapter db = new DBAdapter(this);
db.open();
long id = db.insertContact("12/may", "08:00", "Leeds vs York", "JUME Cup", "ITV, BBC");
id = db.insertContact("13/may", "09:00", "London vs Bath", "JUME Cup", "ITV, BBC2");
db.close();
}
}
However when I try to run it, the debugger shows and error that says:
E/Database(330): android.database.sqlite.SQLiteException: no such table: games: , while compiling: INSERT INTO games(gchannel, ggame, gtime, gdate, gcompetition) VALUES(?, ?, ?, ?, ?);
I’ve trying to change parameters and many things but I haven’t found where the problem is. Can someone help me please?

[Q] Tropo SMS Integration In Android Api

I'm building a complete build of Android with tropo: (Google tropo)
Here's my tropo hosted script in javascript:
Code:
if (typeof number == 'undefined') {//IF the call doesn't come from me (there's no variable set)
var callerId=currentCall.callerID;
var textmessage=currentCall.initialText
hangup()
call('(Put your phone number Here', {network: 'SMS'});
//Analyse message and format it for sending
var message = new Array();
var nbMessages=((textmessage.length())/149) ;//.length() ????? why????
var i=0;
for(i=0;i<nbMessages;i++){
message[i]=callerId+textmessage.substr(i*149,149);
say(message[i]);
wait(1000);
}
hangup()
}
else //SENDING PART:number and text are parameters
{
call(number, {network:"SMS"});
say(text);
}
I've used the CM9 source code for the galaxy s2 that I downloaded and builded following this guide: (Google teamhacksung CyanogenMod9 How to build)
For sending, I simply post an HTTP Post request to my tropo app
Here's the code
I modified the SMSManager.java class in android.telephony package
Code:
public void sendTextMessage(
String destinationAddress, String scAddress, String text,
PendingIntent sentIntent, PendingIntent deliveryIntent) {
if (TextUtils.isEmpty(destinationAddress)) {
throw new IllegalArgumentException("Invalid destinationAddress");
}
if (TextUtils.isEmpty(text)) {
throw new IllegalArgumentException("Invalid message body");
}
/* OLD METHOD FOR SMS BY CARRIER
try {
ISms iccISms = ISms.Stub.asInterface(ServiceManager.getService("isms"));
if (iccISms != null) {
iccISms.sendText(destinationAddress, scAddress, text, sentIntent, deliveryIntent);
}
} catch (RemoteException ex) {
// ignore it
}*/
//My new Method via tropo
//Création de l'objet Tropo SMS
TropoSms sms = new TropoSms(destinationAddress, text, sentIntent,deliveryIntent);
sms.send();
}
/**/
public void sendMultipartTextMessage(
String destinationAddress, String scAddress, ArrayList<String> parts,
ArrayList<PendingIntent> sentIntents, ArrayList<PendingIntent> deliveryIntents) {
if (TextUtils.isEmpty(destinationAddress)) {
throw new IllegalArgumentException("Invalid destinationAddress");
}
if (parts == null || parts.size() < 1) {
throw new IllegalArgumentException("Invalid message body");
}
if (parts.size() > 1) {
/*//OLD METHOD FOR SMS CARRIER
try {
ISms iccISms = ISms.Stub.asInterface(ServiceManager.getService("isms"));
if (iccISms != null) {
iccISms.sendMultipartText(destinationAddress, scAddress, parts,
sentIntents, deliveryIntents);
}
} catch (RemoteException ex) {
// ignore it
}*/
//My tropo Method
for(int i=0; i< parts.size();i++){
TropoSms sms = new TropoSms(destinationAddress, parts.get(i), sentIntents.get(i),deliveryIntents.get(i));
sms.send();
}
} else {
PendingIntent sentIntent = null;
PendingIntent deliveryIntent = null;
if (sentIntents != null && sentIntents.size() > 0) {
sentIntent = sentIntents.get(0);
}
if (deliveryIntents != null && deliveryIntents.size() > 0) {
deliveryIntent = deliveryIntents.get(0);
}
sendTextMessage(destinationAddress, scAddress, parts.get(0),
sentIntent, deliveryIntent);
}
}
Here I created the Tropo SMS class in the android.telephony.tropo package
Code:
/**
*
*/
package android.telephony.tropo;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.telephony.SmsManager;
/**
* @author kevmegforest
*
*/
public class TropoSms {
protected String destinationAddress="Undefined";
protected String message="Undefined";
protected PendingIntent sentIntent;
protected PendingIntent deliveryIntent;
private static String token="1...4c";
public TropoSms(){
}
public TropoSms(String sendAddress, String text, PendingIntent sendIntent, PendingIntent deliverIntent){
destinationAddress=sendAddress;
message=text;
sentIntent=sendIntent;
deliveryIntent=deliverIntent;
}
/**------------------------------------------
* SETTERS AND GETTERS
* @return
*/
public String getDestinationAddress() {
return destinationAddress;
}
public String getMessage() {
return message;
}
//--------------------------------------------------
/**
* Methods
*/
public void send(){ //Success return true //Fail return false
boolean success=true;
this.message=manageText();
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
HttpResponse response;
HttpPost post = new HttpPost("https://api.tropo.com/1.0/sessions");
//Creating JSON object
JSONObject json= new JSONObject();
try {
json.put("token", token);
json.put("number", this.destinationAddress );
json.put("text", this.message);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
success=false;
}
try {
StringEntity se = new StringEntity(json.toString());
post.setEntity(se);
//Post headers Setup
post.addHeader("accept", "application/json");
post.addHeader("content-type","application/json");
response=client.execute(post);
//Checking response
//HOW TO
if(response.getStatusLine().getStatusCode() !=200)
success=false;
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
success =false;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
success=false;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
success=false;
}
this.manageIntent(success);
client.getConnectionManager().shutdown();//Ending connection
}
private void manageIntent(boolean sendsuccess)
{
if(sendsuccess)
{
try {
this.sentIntent.send(Activity.RESULT_OK);
} catch (CanceledException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
try {
this.sentIntent.send(SmsManager.RESULT_ERROR_GENERIC_FAILURE);
} catch (CanceledException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private String manageText()
{
String correctedText=this.message;//The last character in each table is the one to replace with
char characterToReplaceA[]={'à','â','ä','a'};
char characterToReplaceC[]={'ç','c'};
char characterToReplaceE[]={'é','è','ê','ë','e'};
char characterToReplaceI[]={'ì','î','ï','i'};
char characterToReplaceO[]={'ò','ô','ö','o'};
char characterToReplaceU[]={'ù','û','ü','u'};
char characterToReplace[][]={characterToReplaceA,characterToReplaceC,characterToReplaceE,characterToReplaceI,characterToReplaceO,characterToReplaceU};
for(int i=0;i<characterToReplace.length;i++){
for(int j=0;j<(characterToReplace[i].length-1);j++){
correctedText=correctedText.replace(characterToReplace[i][j],characterToReplace[i][characterToReplace[i].length-1]);
correctedText=correctedText.replace(Character.toUpperCase(characterToReplace[i][j]),Character.toUpperCase(characterToReplace[i][characterToReplace[i].length-1]));
}
}
return correctedText;
}
}
The sending part works really well. Since it's an API change I can use any SMS App in android and it would work.
But I have a problem with receiving.
My tropo script can only modify the body message of the sms. So when someone send a SMS message to tropo, I prefixed the body message with 10 characters representing it's phone number like this:
original message: "Hello"
new message:"15551231234Hello"
I then send this message to my phone
The modified class SubmitPdu in android.telephony package in the SMSMessage.java file
It's wherethe SMS app get the sms with the createfrompdu() method
Code:
public static SmsMessage createFromPdu(byte[] pdu, String format) {
SmsMessageBase wrappedMessage;
if (FORMAT_3GPP2.equals(format)) {
wrappedMessage = com.android.internal.telephony.cdma.SmsMessage.createFromPdu(pdu);
} else if (FORMAT_3GPP.equals(format)) {
wrappedMessage = com.android.internal.telephony.gsm.SmsMessage.createFromPdu(pdu);
} else {
Log.e(LOG_TAG, "createFromPdu(): unsupported message format " + format);
return null;
}
//Verify here if it comes from TROPO
Log.d("SMSNumberCompare", "Original number:"+wrappedMessage.getOriginatingAddress());
Log.d("SMSNumberCompare", "Tropo number:"+TropoSmsReceiver.TROPO_APP_PHONE_NUMBER);
if(PhoneNumberUtils.compare(wrappedMessage.getOriginatingAddress(), TropoSmsReceiver.TROPO_APP_PHONE_NUMBER)){
Log.d("SMSNumberCompare", "Comparison:"+(PhoneNumberUtils.compare(wrappedMessage.getOriginatingAddress(), TropoSmsReceiver.TROPO_APP_PHONE_NUMBER)));
//Creating TropoReceive Object
TropoSmsReceiver tropo = (TropoSmsReceiver) wrappedMessage; //Downcasting
tropo.formatFromTropo();
//upcasting
wrappedMessage=tropo;
}
return new SmsMessage(wrappedMessage);
}
And here's my TropoSmsReceiver Class which extends the SmsMessageBase class
Code:
package com.android.internal.telephony.tropo;
import android.telephony.PhoneNumberUtils;
import android.telephony.SmsMessage.MessageClass;
import android.util.Log;
import com.android.internal.telephony.SmsMessageBase;
public class TropoSmsReceiver extends SmsMessageBase {
public final static String TROPO_APP_PHONE_NUMBER="###########";
//My new Methods
//this method will format the text to get the parameters transferred from the tropo text
public void formatFromTropo(){
Log.d("TropoFormat", "old address"+this.originatingAddress.address);
this.originatingAddress.address=PhoneNumberUtils.formatNumber(this.messageBody.substring(0, 10), PhoneNumberUtils.FORMAT_NANP );
Log.d("TropoFormat", "new address"+this.originatingAddress.address);
this.messageBody=this.messageBody.substring(11);
Log.d("TropoFormat", "new Body"+this.messageBody);
}
@Override
public MessageClass getMessageClass() {
// TODO Auto-generated method stub
return null;
}
@Override
public int getProtocolIdentifier() {
// TODO Auto-generated method stub
return 0;
}
@Override
public boolean isReplace() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isCphsMwiMessage() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isMWIClearMessage() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isMWISetMessage() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isMwiDontStore() {
// TODO Auto-generated method stub
return false;
}
@Override
public int getStatus() {
// TODO Auto-generated method stub
return 0;
}
@Override
public boolean isStatusReportMessage() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isReplyPathPresent() {
// TODO Auto-generated method stub
return false;
}
}
The interesting part is my new method formatFromTropo()
But I have a problem, it doesn't work.
It builds sucessfully
In the logcat, the debug log says it goes in the if statement (it says Comparison: true and it's placement is in the if)
But when the tropo.formatFromTropo() is called the catlog has no mention of any log declared in the TropoSmsReceiver File. How is that possible? Can you help me?
It's my first android project (app or android Source change) and java project so you can give me many recommendations(and comments) too.
Thank you

[Q] Sending "string" serially (byte code given)

Hi all,
I am developing an android app for my project which sends data serially, through RS232 + OTG cable, to a circuit developed by me (and the PC code for which is already done and developed in C#). I'm new to android and tried to get help from example apps. i found an app which establishes the serial communication successfully but the problem is that it sends data in the form of byte, but i want data to be sent as a string and also received as a string. portion of the activity of interest is being added which sends binary 10101010... but I want data in string format. like "abcdefg". it must also be noted that this code is ignoring the incoming data but i want the incoming data to be stored in a variable (which i think is not very difficult but it could be handy if someone can also guide about that)
if someone can help, it'll be highly appreciated
Code:
package android_serialport_api.sample;
import java.io.IOException;
import java.util.Arrays;
import android.os.Bundle;
import java.io.*;
import java.util.*;
//import javax.comm.*; // for SUN's serial/parallel port libraries
public class Sending01010101Activity extends SerialPortActivity {
SendingThread mSendingThread;
byte[] mBuffer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sending01010101);
mBuffer = new byte[1024];
Arrays.fill(mBuffer, (byte) 0x55);
if (mSerialPort != null) {
mSendingThread = new SendingThread();
mSendingThread.start();
}
}
@Override
protected void onDataReceived(byte[] buffer, int size) {
// ignore incoming data
}
private class SendingThread extends Thread {
@Override
public void run() {
while (!isInterrupted()) {
try {
if (mOutputStream != null) {
mOutputStream.write(mBuffer);
} else {
return;
}
} catch (IOException e) {
e.printStackTrace();
return;
}
}
}
}
}
not enough info is availabe on the internet on this topic and I only expect help from this forum. its very important for me

Why my items are not redrawn after invoking `invalidateViews()` ?

Why my items are not redrawn after invoking `invalidateViews()` ?
I ask because i try to refresh `listItems` after a bg-thread notify an image rsc was downloaded.
But nothing is updated. Only after exiting and re-entering the new icons are drawn.
I have an activity with `adapter` of type `SettingValueAdapter extends BaseAdapter`
it has a member:
`private SettingsValue[] values;`
it has two interesting methods:
@override
public View getView(int position, View view, ViewGroup parent) {
AddressItem ai= (AddressItem)getItem(position);
DriveToNativeManager dnm = DriveToNativeManager.getInstance();
if (view == null) {
LayoutInflater li = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = li.inflate(R.layout.address_item, null);
}
view.setTag(R.id.addressItem,ai);
view.setTag(position);
view.findViewById(R.id.fullAddressItemCol).setVisibility(View.VISIBLE);
view.findViewById(R.id.addressItemTouch).setVisibility(View.GONE);
view.findViewById(R.id.addressItemImage).setVisibility(View.GONE);
if (ai != null) {
...
}
view.findViewById(R.id.addressItemIconLayout).setVisibility(View.VISIBLE);
Drawable icon = ResManager.GetSkinDrawable(ai.getIcon() + ".bin");
((ImageView)view.findViewById(R.id.addressItemIcon)).setImageDrawable(icon);
..
}
I attach a callback to the bg-thread (c language) image downloading process.
The callback switches to the ui-thread and calls this `refreshList`:
public void refreshSearchIconsOnSearchActivity() {
Runnable refreshViewEvent = new Runnable() {
@override
public void run() {
Activity currentActivity = AppService.getActiveActivity();
if (currentActivity instanceof SearchActivity) {
Log.d("w", "refreshSearchIconsOnSearchActivity callback running in thread "
+ Thread.currentThread().getId() );
//results list
((SearchActivity) currentActivity).refreshList();
}
}
};
AppService.Post(refreshViewEvent);
}
However, the images are done downloading and are not refreshed on the activity.
They are refreshed only when I leave an re-enter the activity.
What am I missing?

Categories

Resources