I am trying to call the function "loadUrl" from a service but not achieving it work
The service is:
MyService.java
package com.yournamespace.yourappname;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import com.exam.probando.PROBANDO;
import com.red_folder.phonegap.plugin.backgroundservice.BackgroundService;
public class MyService extends BackgroundService {
private final static String TAG = MyService.class.getSimpleName();
private String mHelloTo = "World";
#Override
protected JSONObject doWork() {
JSONObject result = new JSONObject();
try {
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String now = df.format(new Date(System.currentTimeMillis()));
String msg = "Hello " + this.mHelloTo + " - its currently " + now;
result.put("Message", msg);
//HERE CALL LoadUrl
Log.d(TAG, msg);
} catch (JSONException e) {
}
return result;
}
#Override
protected JSONObject getConfig() {
JSONObject result = new JSONObject();
try {
result.put("HelloTo", this.mHelloTo);
} catch (JSONException e) {
}
return result;
}
#Override
protected void setConfig(JSONObject config) {
try {
if (config.has("HelloTo"))
this.mHelloTo = config.getString("HelloTo");
} catch (JSONException e) {
}
}
#Override
protected JSONObject initialiseLatestResult() {
// TODO Auto-generated method stub
return null;
}
#Override
protected void onTimerEnabled() {
// TODO Auto-generated method stub
}
#Override
protected void onTimerDisabled() {
// TODO Auto-generated method stub
}
}
I try in MainActivity (PROBANDO) this:
package com.exam.probando;
import android.os.Bundle;
import org.apache.cordova.*;
public class PROBANDO extends CordovaActivity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.init();
// Set by <content src="index.html" /> in config.xml
super.loadUrl(Config.getStartUrl());
//super.loadUrl("file:///android_asset/www/index.html");
}
public void mainLoadUrl() {
String url = "file:///android_asset/www/index2.html";
super.loadUrl(url);
}
}
But don't know how make a call for this..
The plugin is: https://github.com/Red-Folder/Cordova-Plugin-BackgroundService/tree/master/3.1.0
Regards!
PS: Sorry for my bad english..
You need to launch the activity via intent
Intent intent = new Intent(this, PROBANDO.class);
startActivity(intent);
The activity needs to be in your manifest file, as well as the service
Related
I am using telegram API to develop my application. Here is the whole code.
app_info.java:
package com.example.mytelegram;
import org.telegram.api.engine.AppInfo;
public class app_info extends AppInfo {
public app_info(int apiId, String deviceModel, String systemVersion,
String appVersion, String langCode) {
super(apiId, deviceModel, systemVersion, appVersion, langCode);
// TODO Auto-generated constructor stub
}
MemoryApiState.java:
package com.example.mytelegram;
import org.telegram.api.TLConfig;
import org.telegram.api.TLDcOption;
import org.telegram.api.engine.storage.AbsApiState;
import org.telegram.mtproto.state.AbsMTProtoState;
import org.telegram.mtproto.state.ConnectionInfo;
import org.telegram.mtproto.state.KnownSalt;
import java.util.ArrayList;
import java.util.HashMap;
public class MemoryApiState implements AbsApiState {
private HashMap<Integer, ConnectionInfo[]> connections = new HashMap<Integer, ConnectionInfo[]>();
private HashMap<Integer, byte[]> keys = new HashMap<Integer, byte[]>();
private HashMap<Integer, Boolean> isAuth = new HashMap<Integer, Boolean>();
private int primaryDc = 2; // I have tested application with primaryDc=0 to 10
public MemoryApiState(boolean isTest) {
connections.put(1, new ConnectionInfo[]{
new ConnectionInfo(1, 0, isTest ? "149.154.167.40" : "149.154.167.50", 443)
});
}
#Override
public synchronized int getPrimaryDc() {
return primaryDc;
}
#Override
public synchronized void setPrimaryDc(int dc) {
primaryDc = dc;
}
#Override
public synchronized boolean isAuthenticated(int dcId) {
if (isAuth.containsKey(dcId)) {
return isAuth.get(dcId);
}
return false;
}
#Override
public synchronized void setAuthenticated(int dcId, boolean auth) {
isAuth.put(dcId, auth);
}
#Override
public synchronized void updateSettings(TLConfig config) {
connections.clear();
HashMap<Integer, ArrayList<ConnectionInfo>> tConnections = new HashMap<Integer, ArrayList<ConnectionInfo>>();
int id = 0;
for (TLDcOption option : config.getDcOptions()) {
if (!tConnections.containsKey(option.getId())) {
tConnections.put(option.getId(), new ArrayList<ConnectionInfo>());
}
tConnections.get(option.getId()).add(new ConnectionInfo(id++, 0, option.getIpAddress(), option.getPort()));
}
for (Integer dc : tConnections.keySet()) {
connections.put(dc, tConnections.get(dc).toArray(new ConnectionInfo[0]));
}
}
#Override
public synchronized byte[] getAuthKey(int dcId) {
return keys.get(dcId);
}
#Override
public synchronized void putAuthKey(int dcId, byte[] key) {
keys.put(dcId, key);
}
#Override
public synchronized ConnectionInfo[] getAvailableConnections(int dcId) {
if (!connections.containsKey(dcId)) {
return new ConnectionInfo[0];
}
return connections.get(dcId);
}
#Override
public synchronized AbsMTProtoState getMtProtoState(final int dcId) {
return new AbsMTProtoState() {
private KnownSalt[] knownSalts = new KnownSalt[0];
#Override
public byte[] getAuthKey() {
return MemoryApiState.this.getAuthKey(dcId);
}
#Override
public ConnectionInfo[] getAvailableConnections() {
return MemoryApiState.this.getAvailableConnections(dcId);
}
#Override
public KnownSalt[] readKnownSalts() {
return knownSalts;
}
#Override
protected void writeKnownSalts(KnownSalt[] salts) {
knownSalts = salts;
}
};
}
#Override
public synchronized void resetAuth() {
isAuth.clear();
}
#Override
public synchronized void reset() {
isAuth.clear();
keys.clear();
}
}
MainActivity.java:
package com.example.mytelegram;
import java.io.IOException;
import org.telegram.api.TLAbsUpdates;
import org.telegram.api.TLConfig;
import org.telegram.api.TLNearestDc;
import org.telegram.api.auth.TLAuthorization;
import org.telegram.api.auth.TLSentCode;
import org.telegram.api.engine.ApiCallback;
import org.telegram.api.engine.AppInfo;
import org.telegram.api.engine.LoggerInterface;
import org.telegram.api.engine.RpcException;
import org.telegram.api.engine.TelegramApi;
import org.telegram.api.requests.TLRequestAuthSendCall;
import org.telegram.api.requests.TLRequestAuthSendCode;
import org.telegram.api.requests.TLRequestAuthSignIn;
import org.telegram.api.requests.TLRequestHelpGetConfig;
import org.telegram.api.requests.TLRequestHelpGetNearestDc;
import org.telegram.api.requests.TLRequestUpdatesGetState;
import org.telegram.api.updates.TLState;
import android.support.v7.app.ActionBarActivity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends ActionBarActivity {
static Context context;
private static AppInfo ai;
private static void createApi() throws IOException {
String res = "No test";
boolean useTest = res.equals("test");
apiState = new MemoryApiState(useTest);
ai=new AppInfo(App_ID, "Sony", "???", "???", "en");
api = new TelegramApi(apiState, ai, new ApiCallback() {
#Override
public void onAuthCancelled(TelegramApi api) {
}
#Override
public void onUpdatesInvalidated(TelegramApi api) {
}
#Override
public void onUpdate(TLAbsUpdates updates) {
Log.d("tlg", "onUpdate(TLAbsUpdates updates)");
}
});
}
private static void login() throws IOException {
//TLNearestDc dcInfo = api.doRpcCallNonAuth(new TLRequestHelpGetNearestDc());
// api.switchToDc(dcInfo.getNearestDc());
//************ Exception raises here ************
TLConfig config = api.doRpcCallNonAuth(new TLRequestHelpGetConfig()); // I have An IOException Here (e=timeout Exception)
apiState.updateSettings(config);
Log.d("tlg","completed.");
String phone = "+9891********"; // I have tested app with the phone without plus too
Log.d("tlg","Sending sms to phone " + phone + "...");
TLSentCode sentCode = null;
try {
api.doRpcCallNonAuth(new TLRequestAuthSendCode(phone, 1, app_id, "__hash__", "en"));
} catch (RpcException e) {
if (e.getErrorCode() == 303) {
int destDC;
if (e.getErrorTag().startsWith("NETWORK_MIGRATE_")) {
destDC = Integer.parseInt(e.getErrorTag().substring("NETWORK_MIGRATE_".length()));
} else if (e.getErrorTag().startsWith("PHONE_MIGRATE_")) {
destDC = Integer.parseInt(e.getErrorTag().substring("PHONE_MIGRATE_".length()));
} else if (e.getErrorTag().startsWith("USER_MIGRATE_")) {
destDC = Integer.parseInt(e.getErrorTag().substring("USER_MIGRATE_".length()));
} else {
throw e;
}
api.switchToDc(destDC);
sentCode = api.doRpcCallNonAuth(new TLRequestAuthSendCode(phone, 0, app_id, "__hash__", "en"));
} else {
throw e;
}
}
Log.d("tlg","Activation code:");
String code = "123";
TLAuthorization auth = api.doRpcCallNonAuth(new TLRequestAuthSignIn(phone, sentCode.getPhoneCodeHash(), code));
apiState.setAuthenticated(apiState.getPrimaryDc(), true);
Log.d("tlg","Activation complete.");
TLState state = api.doRpcCall(new TLRequestUpdatesGetState());
Log.d("tlg","loaded.");
}
static MemoryApiState apiState;
static TelegramApi api;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=getApplicationContext();
try {
createApi();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
login();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//workLoop();
}
}
I have added telegram-api library (telegram-api-1.1.127-shadow.jar) in my eclipse 'libs' folder. The problem is Timeout Exception in MainActivity.java when I want to call RPC. Where is the problem? What should I do? My OS is windows 8.1 . I am searching for 2 whole days. I have read github codes too. They are very complicated for me. I can not figure out what should I do?
I have added INTERNET and ACCESS_NETWORK_STATE permisions to AndroidManifest.xml. I allways check the network connection when my application runs.
I found the problem in your code:
In MemoryApiState you should put, in the 'connections' map, 'primaryDc' as key and not '1'.
My code receives no crash errors. When I run the App and click the button, a Toast should show, but it doesn't.
Here is my IntentService
package com.example.flas;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.flas.JSONParser;
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.util.Log;
import android.widget.Toast;
public class SampleIntentService extends IntentService {
public static final int DOWNLOAD_ERROR = 10;
public static final int DOWNLOAD_SUCCESS = 11;
String latbus;
String lonbus;
String latsta;
String Employernumber;
String lonsta;
String numrout;
String nomsta;
JSONParser jsonParser = new JSONParser();
private static final String url_product_detials = "http://********/get_loc_details2.php";
private static final String TAG_IDLOCBUS = "idlocbus";
private static final String TAG_BUSNUMBER = "BusNumber";
private static final String TAG_BUSLATITUDE = "BusLatitude";
private static final String TAG_BUSLONGITUDE = "Buslongitude";
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "product";
public SampleIntentService() {
super(SampleIntentService.class.getName());
// TODO Auto-generated constructor stub
}
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
String url = intent.getStringExtra("url");
final ResultReceiver receiver = intent.getParcelableExtra("receiver");
Bundle bundle = new Bundle();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", url));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(
url_product_detials, "GET", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
int success = json.getInt(TAG_SUCCESS);
// successfully received product details
JSONArray productObj = json
.getJSONArray(TAG_PRODUCT); // JSON Array
// get first product object from JSON Array
JSONObject product = productObj.getJSONObject(0);
// product with this pid found
// display product data in EditText
String aa = product.getString(TAG_IDLOCBUS);
String bb = product.getString(TAG_BUSNUMBER);
String latb = product.getString(TAG_BUSLATITUDE);
String lonb = product.getString(TAG_BUSLONGITUDE);
bundle.putString("filePath", lonb + latb);
receiver.send(DOWNLOAD_SUCCESS, bundle);
} catch (Exception e) {
// TODO: handle exception
receiver.send(DOWNLOAD_ERROR, Bundle.EMPTY);
e.printStackTrace();
}
}
}
My MainActivity that calls my IntentService
public class MainActivity extends Activity implements OnClickListener {
ProgressBar pd;
SampleResultReceiver resultReceiever;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resultReceiever = new SampleResultReceiver(new Handler());
pd = (ProgressBar) findViewById(R.id.downloadPD);
}
private class SampleResultReceiver extends ResultReceiver {
public SampleResultReceiver(Handler handler) {
super(handler);
// TODO Auto-generated constructor stub
}
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
// TODO Auto-generated method stub
switch (resultCode) {
case SampleIntentService.DOWNLOAD_ERROR: {
Toast.makeText(getApplicationContext(), "error in download", Toast.LENGTH_SHORT).show();
pd.setVisibility(View.INVISIBLE);
}
break;
case SampleIntentService.DOWNLOAD_SUCCESS: {
String filePath = resultData.getString("filePath");
Toast.makeText(getApplicationContext(), "image download via IntentService is done", Toast.LENGTH_SHORT).show();
pd.setIndeterminate(false);
pd.setVisibility(View.INVISIBLE);
}
break;
}
super.onReceiveResult(resultCode, resultData);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent startIntent = new Intent(MainActivity.this, SampleIntentService.class);
startIntent.putExtra("receiver", resultReceiever);
String aaa = "5";
startIntent.putExtra("url", aaa);
startService(startIntent);
pd.setVisibility(View.VISIBLE);
pd.setIndeterminate(true);
}
public void onClick2(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "image download via IntentService is done", Toast.LENGTH_SHORT).show();
}
}
My JSON Class works fine, I tried it in another App and I got not error.
In my AndroidManifest.xml ...
I tried this:
<service android:name="com.example.pfecuspart.SampleIntentService"
android:exported="false">
<intent-filter>
<action android:name="org.example.android.myservicedemo.IService" />
</intent-filter>
</service>
I also tried this:
<service android:name="com.example.pfecuspart.SampleIntentService"
android:enabled="true">
</service>
I dont think onClick2 is doing anything, its not overriding the onClick.
do you need to move;
Toast.makeText(getApplicationContext(),
"image download via IntentService is done",
Toast.LENGTH_SHORT).show();
from onClick2, to onClick.
Maybe try replacing getApplicationContext() with MainActivity.this
I am trying out the WebSockets with Fallbacks transports for Android, Node.js and Atmosphere example. I get an the following error:
/home/mofa/NetBeansProjects/App/src/com/jullio/advisor/wAsyncChat.java:87: error: cannot access JsonParseException
return mapper.readValue(data, Message.class);
class file for org.codehaus.jackson.JsonParseException not found
/home/mofa/NetBeansProjects/App/src/com/jullio/advisor/wAsyncChat.java:68: error: cannot access ObjectCodec
return mapper.writeValueAsString(data);
class file for org.codehaus.jackson.ObjectCodec not found
Here is the androidchat code:
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.atmosphere.wasync.ClientFactory;
import org.atmosphere.wasync.Decoder;
import org.atmosphere.wasync.Encoder;
import org.atmosphere.wasync.Event;
import org.atmosphere.wasync.Function;
import org.atmosphere.wasync.Request;
import org.atmosphere.wasync.RequestBuilder;
import org.atmosphere.wasync.impl.AtmosphereClient;
import org.codehaus.jackson.map.ObjectMapper;
import java.io.IOException;
import java.util.Date;
public class wAsyncChat extends Activity {
private Button bt;
private TextView tv;
private String serverIpAddress = "http://10.0.2.2:8080";
private final static ObjectMapper mapper = new ObjectMapper();
private final Handler uiHandler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.main);
bt = (Button) findViewById(R.id.myButton);
tv = (TextView) findViewById(R.id.myTextView);
try {
AtmosphereClient client = ClientFactory.getDefault().newClient(AtmosphereClient.class);
RequestBuilder request = client.newRequestBuilder()
.method(Request.METHOD.GET)
.uri(serverIpAddress + "/chat")
.trackMessageLength(true)
.encoder(new Encoder<Message, String>() {
#Override
public String encode(Message data) {
try {
return mapper.writeValueAsString(data);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
})
.decoder(new Decoder<String, Message>() {
#Override
public Message decode(Event type, String data) {
data = data.trim();
// Padding
if (data.length() == 0) {
return null;
}
if (type.equals(Event.MESSAGE)) {
try {
return mapper.readValue(data, Message.class);
} catch (IOException e) {
e.printStackTrace();
return null;
}
} else {
return null;
}
}
})
.transport(Request.TRANSPORT.WEBSOCKET);
final org.atmosphere.wasync.Socket socket = client.create();
socket.on("message", new Function<Message>() {
#Override
public void on(final Message t) {
uiHandler.post(new Runnable() {
#Override
public void run() {
Date d = new Date(t.getTime());
tv.append("Author " + t.getAuthor() + "# " + d.getHours() + ":" + d.getMinutes() + ": " + t.getMessage() + "\n");
}
});
}
}).on(new Function<Throwable>() {
#Override
public void on(Throwable t) {
tv.setText("ERROR 3: " + t.getMessage());
t.printStackTrace();
}
}).open(request.build());
bt.setOnClickListener(new OnClickListener() {
String name = null;
public void onClick(View v) {
try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
if (name == null) {
name = str;
}
socket.fire(new Message(name, str));
et.setText("");
Log.d("Client", "Client sent message");
} catch (Throwable e) {
tv.setText("ERROR 3: " + e.getMessage());
e.printStackTrace();
}
}
});
} catch (Throwable e) {
tv.setText("Unable to connect: " + e.getMessage());
e.printStackTrace();
}
}
}
I have the library for nodeserver connection. You can use it from git
SocketIO socketio = new SocketIO() {
#Override
public void onConnect() {
}
#Override
public void onDisconnect() {
}
#Override
public void onMessage(String message) {
Log.d("===Server Answer====",message);
}
};
socketio.Connect("192.168.0.1", 9000);
after onConnect() send the message:
socketio.send("Your message to socket");
it work with latest socketIO, and use RFC 6455 websocket protocol
I check if a string is NULL in a Thread, if its null, the Handler starts
a Runnable which starts a new Activity.
Everything works fine, but, after the new activity is displayed it switches back to the calling Activity and it crashes.
Here is a code snippet.
if(username==null)
{
dialogs.dismiss();
handlers.post(new MyRunable());
}
and Runnable is
public class MyRunable implements Runnable
{
public void run(){
Toast.makeText(ListActivity.this, "Your Connection is too slow",Toast.LENGTH_LONG).show();
startActivity(new Intent(ListActivity.this,Anim.class));
}
}
Here is my Full Source
package com.cram;
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class BuddyListActivity extends Activity
{
String ss;
private static ProgressDialog dialogs,dialog;
private Thread downloadThreads;
boolean results=false;
Context ctx;
String[]ddd;
ListView lv1;
String [] icons;
BuddyDbAdapter adapter;
NetworkInfo netinfo;
Cursor cursor;
String values;
GetBuddy gb;
BuddyDB db;
String[] username;
String[] firstname;
String[] lastname;
String[] avatar;
String[] id;
File[] iconss;
Handler handlers;
boolean ready=false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.buddy);
db=new BuddyDB(BuddyListActivity.this);
Typeface font = Typeface.createFromAsset(getAssets(),"fonts/Fortheloveofhate.ttf");
TextView btxt = (TextView) findViewById(R.id.textbuddy);
btxt.setTypeface(font);
ctx=getApplicationContext();
lv1=(ListView)findViewById(R.id.list22);
netinfo=null;
adapter=new BuddyDbAdapter(BuddyListActivity.this);
netinfo=checkDataConnection(getApplicationContext());
handlers = new Handler();
adapter.open();
if(netinfo!=null)
{
downloadThreads = (Thread) getLastNonConfigurationInstance();
if (downloadThreads != null && downloadThreads.isAlive()) {
dialog = ProgressDialog.show(this, "Download", "downloading");
}
startdownload();
}
if(netinfo==null)
{
cursor=adapter.showBuddy();
if (cursor==null||cursor.moveToFirst()==false)
{
AlertDialog.Builder buddybox = new AlertDialog.Builder(this);
buddybox.setMessage("You have No Buddies Yet douche!!");
buddybox.setNeutralButton("Okay", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(getBaseContext(),Anim.class));
}
});
buddybox.setCancelable(false);
buddybox.show();
}
else
{
cursor.moveToFirst();
int j=0;
ddd=new String[cursor.getCount()];
icons=new String [cursor.getCount()];
do
{
String firstName = cursor.getString(cursor.getColumnIndex(BuddyDbAdapter.BUDDY_FISTNAME));
String lastname = cursor.getString(cursor.getColumnIndex(BuddyDbAdapter.BUDDY_LASTNAME));
String Avatar = cursor.getString(cursor.getColumnIndex(BuddyDbAdapter.AVATAR));
ddd[j]=firstName+" "+lastname;
Log.d("Test", ddd[j]);
icons[j]=Avatar;
Log.d("Test", icons[j]);
j++;
}while(cursor.moveToNext());
iconss= new File[icons.length];
Log.d("Test",icons.length+"");
for (int q = 0; q < icons.length; q++) {
iconss[q] = new File(Download.ROOT +"/"+ icons[q]+".jpg");
Log.d("Test", iconss[q].getAbsolutePath().toString());
}
//adapter.close();
lv1.setAdapter(new BuddyAdapter(BuddyListActivity.this,R.layout.list1,ddd,iconss));
onDestroy();
}
}
}
private void box() {
// TODO Auto-generated method stub
cursor=adapter.showBuddy();
if (cursor==null||cursor.moveToFirst()==false)
{
dialogs.dismiss();
AlertDialog.Builder buddybox = new AlertDialog.Builder(this);
buddybox.setMessage("You have No Buddies Yet ass!!");
buddybox.setNeutralButton("Okay", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(getBaseContext(),Anim.class));
}
});
buddybox.setCancelable(false);
buddybox.show();
}
}
private NetworkInfo checkDataConnection(Context applicationContext) {
final ConnectivityManager connMgr = (ConnectivityManager)BuddyListActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkinfo=null;
final android.net.NetworkInfo wifi =connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobile =connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if(wifi.isConnected()||mobile.isConnected())
{networkinfo=connMgr.getActiveNetworkInfo();
return networkinfo;
}
else
{
return null;
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (adapter != null) {
adapter.close();
}
}
#Override
protected void onStop()
{
super.onStop();
finish();
}
private void startdownload() {
dialogs = ProgressDialog.show(BuddyListActivity.this, "Contacting Our Servers", "Geting Your Buddies Avatar");
downloadThreads = new MyThread();
downloadThreads.start();
}
public class MyThread extends Thread {
#Override
public void run() {
try {
new Thread();
GetBuddy tt=new GetBuddy();
String xml=tt.get();
if(xml==null)
{ dialogs.dismiss();
handlers.post(new MyRunable());
ready=false;
//downloadThreads.suspend();
}
final Download cd = new Download();
results = cd.downloadBitmap();
if(results)
{
BuddyParse bp=new BuddyParse();
try {
username=bp.show(xml);
// if(username==null)
// { dialogs.dismiss();
// handlers.post(new MyRunable());
// //downloadThreads.suspend();
// }
firstname=bp.firstname();
lastname=bp.lastname();
avatar=bp.avatar();
id=bp.id();
adapter.deleteAll();
ready=true;
}
catch (ParserConfigurationException e)
{
e.printStackTrace();
}
catch (SAXException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
// Log.d("len", username.length+"");
for(int k=0; k<username.length;k++)
{
adapter.insertBuddy(id[k], username[k], firstname[k], lastname[k], avatar[k]);
Log.d("Test", id[k]+username[k]+firstname[k]+lastname[k]+avatar[k]+"");
}
box();
cursor=adapter.showBuddy();
cursor.moveToFirst();
int i=0;
ddd=new String[cursor.getCount()];
icons=new String [cursor.getCount()];
do
{
String firstName = cursor.getString(cursor.getColumnIndex(BuddyDbAdapter.BUDDY_FISTNAME));
String lastname = cursor.getString(cursor.getColumnIndex(BuddyDbAdapter.BUDDY_LASTNAME));
String Avatar = cursor.getString(cursor.getColumnIndex(BuddyDbAdapter.AVATAR));
ddd[i]=firstName+" "+lastname;
Log.d("Test", ddd[i]);
icons[i]=Avatar;
Log.d("Test",icons[i]);
i++;
}while(cursor.moveToNext());
iconss= new File[avatar.length];
for (int k = 0; k < avatar.length; k++) {
iconss[k] = new File(Download.ROOT+"/"+avatar[k]+".jpg");
Log.d("Test", iconss[k].getAbsolutePath()+"thread");
//Log.d("Test", ddd[k]);
}
if (results&&ready)
{
dialogs.dismiss();
handlers.post(new MyRuns());
}
}
// else
// { dialogs.dismiss();
// handlers.post(new MyRunable());
//
// }
}finally {
}
}
}
public class MyRuns implements Runnable {
public void run() {
ready=true;
lv1.setAdapter(new BuddyAdapter(ctx,R.layout.list1,ddd,iconss));
onDestroy();
}
}
public class MyRunable implements Runnable {
public void run() {
//Toast.makeText(BuddyListActivity.this, "Your Connection is too slow", Toast.LENGTH_LONG).show();
startActivity(new Intent(BuddyListActivity.this,Anim.class));
}
}
}
use main thread to start your thread check runOnUiThread(Runnable action)
Setting RETURN in the try catch block and setting
android:noHistory="true" in Android Manifest for all activities fixed my problem
If you are trying to create an async task in a different thread I would recommend you to use the following class:
private final class MyRunnable extends
AsyncTask<Void, Void, Document> {
protected Document doInBackground(Void... params) {
}
protected void onPostExecute(Document result) {
}
}
You only have to change the parameters.
More info here:
http://developer.android.com/reference/android/os/AsyncTask.html
Finish your current activity when starting another activity from runnable .
Please guide in the following class what I should save in.
Please remember I am using only one string which is I am retriving from getextra method and there is nothing which I think I should store in the following overridden method.
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
}
Can you guide me what to store in onsave instance method and what not to?
package com.wozzon.activity;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import com.wozzon.json.JSONService;
import com.wozzon.model.SearchCriteria;
import com.wozzon.pl.UIFactory;
import com.wozzon.util.Util;
import com.wozzon.util.WLConstants;
public class HomeBrowse extends Activity implements OnItemClickListener{
private final static String TAG = HomeBrowse.class.getSimpleName();
private ArrayList<BrowseRow> model=new ArrayList<BrowseRow>();
private BrowseAdapter adapter;
private ListView list;
private TextView browseTitle;
private TextView changeLink;
private SearchCriteria sc =SearchCriteria.getInstance();
private JSONArray jsonArray;
private ProgressDialog m_ProgressDialog = null;
private Runnable progressRunnable;
#Override
public void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.browse);
String errorMsg =Util.getExtraValue(getIntent().getExtras(), WLConstants.ERROR_MSG);
list =(ListView)findViewById(R.id.browse_cats);
if(errorMsg!= null){
UIFactory.displayAlert(new AlertDialog.Builder(HomeBrowse.this), "Status", errorMsg);
}
progressRunnable = new Runnable(){
#Override
public void run() {
try {
loadData();
} catch (Throwable e) {
Log.e(TAG, e.getMessage());
}
runOnUiThread(returnRes);
}
};
m_ProgressDialog = ProgressDialog.show(HomeBrowse.this,
"Please wait...", "Loading ...", true);
Thread thread = new Thread(progressRunnable);
thread.start();
} catch (Throwable e) {
Log.e(TAG, e.getMessage());
Util.handleError(HomeBrowse.this, HomeBrowse.class, e.getMessage());
//UIFactory.displayAlert(new AlertDialog.Builder(HomeBrowse.this), "Error Loading categories", e.getMessage());
}
}
private void loadData()throws Throwable{//loading object
jsonArray = JSONService.getJsonArray(getResources().getString(R.string.catJson));
}
private void fillResultRows(JSONArray jsonArray, BrowseAdapter adapter)throws Throwable{
BrowseRow br = null;
try {
for(int a=0; a<jsonArray.length(); a++){
JSONObject jsonObj = jsonArray.getJSONObject(a);
br = new BrowseRow();
br.name=jsonObj.getString("title");
br.image=jsonObj.getString("image");
br.searchType = jsonObj.getInt("searchType");
if(jsonObj.has("categoryIds")){
br.categoryIds = jsonObj.getString("categoryIds").replaceAll("-", ",");
}
if(jsonObj.has("subCategoryIds")){
br.subCategoryIds = jsonObj.getString("subCategoryIds").replaceAll("-", ",");
}
adapter.add(br);
}
} catch (Throwable e) {
throw e;
}
}
class BrowseAdapter extends ArrayAdapter<BrowseRow> {
BrowseAdapter() {
super(HomeBrowse.this, android.R.layout.simple_list_item_1, model);
}
public View getView(int position, View convertView,
ViewGroup parent) {
View row=convertView;
ResultWrapper wrapper=null;
if (row==null) {
LayoutInflater inflater=getLayoutInflater();
row=inflater.inflate(R.layout.browse_row, null);
wrapper=new ResultWrapper(row);
row.setTag(wrapper);
}
else {
wrapper=(ResultWrapper)row.getTag();
}
wrapper.populateFrom(model.get(position));
return(row);
}
}
class ResultWrapper {
private TextView name;
private String catIds="0";
private String subCatIds="0";
private ImageView image;
private int searchType;
private View row=null;
ResultWrapper(View row) {
this.row=row;
}
void populateFrom(BrowseRow r) {
getName().setText(r.name);
getIcon().setImageResource(getImageIcon(Integer.parseInt(r.image)));
catIds =r.categoryIds;
subCatIds = r.subCategoryIds;
searchType =r.searchType;
}
TextView getName() {
if (name==null) {
name=(TextView)row.findViewById(R.id.browse_row_name);
}
return name;
}
ImageView getIcon() {
if (image==null) {
image=(ImageView)row.findViewById(R.id.browse_row_icon);
}
return image;
}
}
private int getImageIcon(int catId){
int imageSource=R.drawable.all_cats;
switch(catId){
case WLConstants.CATEGORY_FILM: imageSource =R.drawable.film; break;
case WLConstants.CATEGORY_MUSIC: imageSource =R.drawable.music; break;
case WLConstants.CATEGORY_ARTS: imageSource =R.drawable.art; break;
case WLConstants.CATEGORY_KIDS: imageSource =R.drawable.museum; break;
case WLConstants.CATEGORY_GALLERY_MUSEUM: imageSource =R.drawable.kids; break;
case WLConstants.CATEGORY_COMEDY: imageSource =R.drawable.comedy; break;
case WLConstants.CATEGORY_NIGHT_CLUBS: imageSource =R.drawable.clubs; break;
case WLConstants.CATEGORY_ATTRACTION: imageSource =R.drawable.touristattractions; break;
case WLConstants.CATEGORY_VARIOUS_EVENTS: imageSource =R.drawable.all_cats; break;
case WLConstants.CATEGORY_ALL_FOOD_DRINK: imageSource =R.drawable.restaurants; break;
}
return imageSource;
}
#Override
public void onItemClick(AdapterView<?> adp, View view, int item, long arg3) {
try {
if("".equals(sc.getSearchLocation()) && (!(Util.locationFound(sc.getGeoLocation()) && sc.isUK()))){
UIFactory.displayAlert(new AlertDialog.Builder(HomeBrowse.this), "Error", "Please provide location");
return;
}
ResultWrapper wrap = (ResultWrapper)view.getTag();
sc.setCategoryIds(wrap.catIds);
sc.setSubCategoryIds(wrap.subCatIds);
sc.setSearchType(wrap.searchType);
goSearch();
} catch (Throwable e) {
Log.e(TAG, e.getMessage());
Util.handleError(HomeBrowse.this, HomeBrowse.class, e.getMessage());
//UIFactory.displayAlert(new AlertDialog.Builder(this), "Error", e.getMessage());
}
}
private void applyListener(){
list.setOnItemClickListener(this);
changeLink.setOnClickListener(onclickListener);
}
private final void goSearch(){
try {
sc.setSearchString("");
Intent mainIntent = new Intent(HomeBrowse.this,SearchResults.class);
startActivity(mainIntent);
} catch (Throwable e) {
Log.e(TAG, e.getMessage());
Util.handleError(HomeBrowse.this, HomeBrowse.class, e.getMessage());
}
}
public OnClickListener onclickListener = new OnClickListener(){
// #Override
public void onClick(View aView) {
try {
int componentId =aView.getId();
switch(componentId){
case R.id.tv_changeDateType:
Intent intent = new Intent(HomeBrowse.this,TimeLocationSettings.class);
startActivity(intent);
break;
}
} catch (Exception e) {
Log.e(TAG, e.getMessage());
Util.handleError(HomeBrowse.this, HomeBrowse.class, e.getMessage());
}
}
};
private void configComponents(){
String titleStr,location = "";
String dateCrtStr = Util.getDateCritieraStr(sc.getDateCriteria());
titleStr= dateCrtStr;
if(!"".equals(sc.getSearchLocation())){
location = sc.getSearchLocation();
}else if(sc.isNearMe()){
location="Near me";
}else{
location = "Postcode or town";
}
titleStr = titleStr + " - "+ location;
browseTitle.setText(titleStr);
changeLink.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
}
public class BrowseRow {
private String name = "";
private String image = "";
private String categoryIds="0";
private String subCategoryIds="0";
private int searchType=1;
}
private Runnable returnRes = new Runnable() {
#Override
public void run() {
try {
browseTitle = (TextView)findViewById(R.id.browsePageTite);
changeLink = (TextView)findViewById(R.id.tv_changeDateType);
changeLink.setText(Html.fromHtml("<a href='#'>Change</a>"));
adapter=new BrowseAdapter();
applyListener();
configComponents();
fillResultRows(jsonArray, adapter);
if(jsonArray == null){
UIFactory.displayAlert(new AlertDialog.Builder(HomeBrowse.this), "Error", "Error Loading categories");
return;
}
list.setAdapter(adapter);
} catch (Throwable e) {
e.printStackTrace();
}
m_ProgressDialog.dismiss();
}
};
}
Not necessarily everything, because
The default implementation takes care of most of the UI per-instance state for you by calling onSaveInstanceState() on each view in the hierarchy that has an id, and by saving the id of the currently focused view (all of which is restored by the default implementation of onRestoreInstanceState(Bundle)).
via http://developer.android.com/reference/android/app/Activity.html#onSaveInstanceState(android.os.Bundle)
but if you override, you have to handle entire state by yourself.
You should be saving everything that describes the view's state that isn't saved elsewhere.
Save where the user is in a EditText, what value the EditText has, what dialog is currently displayed, etc. Your application should be able to reconstruct the exact state it was in from the bundle returned to in when it is paused by the user leaving the application and returning to it.