Data not stored into realm database - java

java.lang.IllegalStateException: Your Realm is opened from a thread
without a Looper and you provided a callback, we need a Handler to
invoke your callback
I'm Writing a code that will do in background- read from a text file(inside assets) and then placing them into a realm database.But i seem to get this error
"java.lang.IllegalStateException: Your Realm is opened from a thread without a Looper and you provided a callback, we need a Handler to invoke your
callback"
In my onCreate i have this
Realm.init(context);
realm = Realm.getDefaultInstance();
ParseInBackground task = new ParseInBackground();
task.execute();
and in the do-in-background task of AsyncTask i got this
try {
realm = Realm.getDefaultInstance();
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm bgRealm) {
final ModelClass modelClass = bgRealm.createObject(ModelClass.class);
try {
InputStream file = getAssets().open("goodie.txt");
reader = new BufferedReader(new InputStreamReader(file));
final String[] line = {reader.readLine()};
while (line[0] != null) {
handler.post(new Runnable() {
#Override
public void run() {
try {
line[0] = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
String[] namelist = line[0].split(":");
String iWord = namelist[0];
String iDesc = namelist[1];
modelClass.setName(iWord);
modelClass.setDesc(iDesc);
count++;
}
});
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (realm != null)
realm.close();
}
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
Toast.makeText(MainActivity.this, "Added " + count + "items", Toast.LENGTH_SHORT).show();
}
}, new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
}
}
);
} catch (Exception e) {
e.printStackTrace();
}
and a Model class called ModelClass has this
private String name;
private String desc;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
Desperately in need of help.Thanks in advance

Check http://developer.android.com/reference/android/os/Handler.html and http://developer.android.com/reference/android/os/Looper.html
Basically Realm need a way to communicate with your thread when doing asyc query, on Android, naturally Looper and Handler is the way to go.
Check this for more sample code.
https://github.com/realm/realm-java/tree/master/examples/threadExample

You need to remove Handler.post(...) from within the execute callback.
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm bgRealm) {
final ModelClass modelClass = bgRealm.createObject(ModelClass.class);
try {
InputStream file = getAssets().open("goodie.txt");
reader = new BufferedReader(new InputStreamReader(file));
final String[] line = {reader.readLine()};
while (line[0] != null) {
try {
line[0] = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
String[] namelist = line[0].split(":");
String iWord = namelist[0];
String iDesc = namelist[1];
modelClass.setName(iWord);
modelClass.setDesc(iDesc);
count++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (realm != null)
realm.close();
}
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
Toast.makeText(MainActivity.this, "Added " + count + "items", Toast.LENGTH_SHORT).show();
}
}, new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
}
}
);
} catch (Exception e) {
e.printStackTrace();
}
I hope this helps.

Related

How to stop app from accessing the internet when a blacklisted app is installed

I have an app which automatically fetch data online whenever it is opened. I would like to make it a way that the app will only check for update online when a blacklisted app is not detected.
This is the update core.
public class UpdateCore extends AsyncTask<String, String, String> {
private static final String TAG = "NetGuard.Download";
private Context context;
private Listener listener;
private PowerManager.WakeLock wakeLock;
private HttpURLConnection uRLConnection;
private InputStream is;
private TorrentDetection torrent;
private BufferedReader buffer;
private String url;
public interface Listener {
void onLoading();
void onCompleted(String config) throws Exception;
void onCancelled();
void onException(String ex);
}
public UpdateCore(Context context, String url, Listener listener) {
this.context = context;
this.url = url;
this.listener = listener;
}
#Override
protected void onPreExecute() {
listener.onLoading();
}
#Override
protected String doInBackground(String... args) {
try {
String api = url;
if(!api.startsWith("http")){
api = new StringBuilder().append("http://").append(url).toString();
}
URL oracle = new URL(api);
HttpClient Client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(oracle.toURI());
HttpResponse response = Client.execute(httpget);
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
in, "iso-8859-1"), 8);
//BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
str.append(line);
}
in.close();
return str.toString();
} catch (Exception e) {
return "error";
} finally {
if (buffer != null) {
try {
buffer.close();
} catch (IOException ignored) {
}
}
if (is != null) {
try {
is.close();
} catch (IOException ignored) {
}
}
if (uRLConnection != null) {
uRLConnection.disconnect();
}
}
}
#Override
protected void onCancelled() {
super.onCancelled();
// Log.i(TAG, "Cancelled");
// pd.dismiss();
listener.onCancelled();
}
#Override
protected void onPostExecute(String result) {
// wakeLock.release();
//nm.cancel(1);
// pd.dismiss();
try
{
if (result.equals("error"))
{
listener.onException(result);
}
else {
listener.onCompleted(result);
}
}
catch (Exception e)
{
listener.onException(e.getMessage());
}
}
}
This is the detection code
public class TorrentDetection
{
private Context context;
private String[] items;
private TorrentDetection.TorrentListener listener;
private Timer timer;
private Handler handler;
public interface TorrentListener {
public void detected(ArrayList pkg);
}
public TorrentDetection(Context c, String[] i, TorrentListener listener) {
context = c;
items = i;
this.listener = listener;
}
private boolean check(String uri)
{
PackageManager pm = context.getPackageManager();
boolean app_installed = false;
try
{
pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
app_installed = true;
}
catch (PackageManager.NameNotFoundException e)
{
app_installed = false;
}
return app_installed;
}
void check() {
ArrayList arrayList2 = new ArrayList();
for (String pack : items)
{
if(check(pack)){
arrayList2.add(pack);
}
}
if (arrayList2.size() > 0)
{
listener.detected(arrayList2);
stop();
}
}
public void start() {
handler = new Handler();
timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run()
{
handler.post(new Runnable() {
public void run()
{
check();
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 3000);
}
public void stop() {
if(timer != null){
timer.cancel();
timer = null;
}
if(handler != null){
handler = null;
}
}
}
The torrent detection code checks if the following apps are installed and returns a message that an unsupported app is installed.
public class Constraints
{
public static String updater = "https://pastenord.org/raw/random";
public static String[] torrentList = new String[]{
"com.guoshi.httpcanary",
"com.adguard.android.contentblocker"};
}
In my MainActivity this initiates the detection before the online update is done with torrent.start();
void update() {
torrent.start();
new UpdateCore(this, Constraints.updater, new UpdateCore.Listener() {
#Override
public void onLoading() {
}
#Override
public void onCompleted(final String config) {
try {
final JSONObject obj = new JSONObject(MilitaryGradeEncrypt.decryptBase64StringToString(config, Constraints.confpass));
if (Double.valueOf(obj.getString("Version")) <= Double.valueOf(conts.getConfigVersion())) {
} else {
new SweetAlertDialog(MainActivity.this, SweetAlertDialog.CUSTOM_IMAGE_TYPE)
.setTitleText("Update")
.setContentText("\n" + obj.getString("Message"))
.setConfirmText("Yes,Update it!")
.setCustomImage(R.drawable.ic_update)
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sDialog) {
sDialog.dismissWithAnimation();
welcomeNotif();
restart_app();
try {
db.updateData("1", config);
sp.edit().putString("CurrentConfigVersion", obj.getString("Version")).commit();
} catch (JSONException e) {}
}
})
.show();
}
} catch (Exception e) {
// Toast.makeText(MainActivity.this, e.getMessage() , 0).show();
}
}
#Override
public void onCancelled() {
}
#Override
public void onException(String ex) {
}
}).execute();
}
}
It then makes a popup when an unsupported app is detected with this.
torrent = new TorrentDetection(this, Constraints.torrentList, new TorrentDetection.TorrentListener() {
#Override
public void detected(ArrayList pkg)
{
stopService();
new AlertDialog.Builder(MainActivity.this)
.setTitle("unsupported App!")
.setMessage(String.format("%s", new Object[]{TextUtils.join(", ", (String[]) pkg.toArray(new String[pkg.size()]))}))
.setPositiveButton("OK", null)
//.setAnimation(Animation.SLIDE)
.setCancelable(false)
.create()
//.setIcon(R.mipmap.ic_info, Icon.Visible)
.show();
}
});
I would like the make the app only check for online update only when done of the blacklisted apps are installed. Any form of help is welcomed and appreciated.
use this method to check if an application is installed or not
public boolean isPackageInstalled(String packageName, PackageManager packageManager) {
try {
packageManager.getPackageInfo(packageName, 0);
return true;
} catch (PackageManager.NameNotFoundException e) {
return false;
}
}
then to check, simply call:
PackageManager pm = context.getPackageManager();
boolean isInstalled = isPackageInstalled("com.somepackage.name", pm);
// simply put an if statemement
if(!isInstalled){
//do your update here
}
else{
//display you have installed a blacklisted app
}
sidenote, if you are targeting android 11 and above, you need to provide the information about the packages you want to find out about in the manifest like this
<queries>
<!--Add queries here-->
<package android:name="com.somepackage.name" />
</queries>

java.lang.IllegalArgumentException: Given work is not active exception in Oreo while i m using unique job id across the app

How to handle this kind of exception? Given work is not active exception in Oreo while i m using unique job id across the app.
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:353)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
at java.util.concurrent.FutureTask.run(FutureTask.java:271)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
Caused by: java.lang.IllegalArgumentException: Given work is not active: JobWorkItem{id=2 intent=Intent { cmp=com.virinchi.mychat/com.virinchi.receiver.AnalysticsSubmit } dcount=1}
at android.app.job.JobParameters.completeWork(JobParameters.java:221)
at android.support.v4.app.JobIntentService$JobServiceEngineImpl$WrapperWorkItem.complete(JobIntentService.java:267)
at android.support.v4.app.JobIntentService$CommandProcessor.doInBackground(JobIntentService.java:393)
at android.support.v4.app.JobIntentService$CommandProcessor.doInBackground(JobIntentService.java:382)
at android.os.AsyncTask$2.call(AsyncTask.java:333)
at java.util.concurrent.FutureTask.run(FutureTask)
public class AnalysticsSubmit extends JobIntentService {
private static String TAG = "AnalysticsSubmit";
/**
* Unique job ID for this service.
*/
/**
* Convenience method for enqueuing work in to this service.
*/
public static void enqueueWork(Context context, Intent work) {
try{
enqueueWork(context, AnalysticsSubmit.class, JOB_ID, work);
}catch (Exception ex){
Log.e(TAG, "enqueueWork: ex"+ex.getMessage() );
}
}
#Override
protected void onHandleWork(Intent intent) {
try {
UtilsUserInfo userInfo = new UtilsUserInfo(DocApplication.getContext());
int width = 0;
int height = 0;
String widthstr = "0";
String heightstr = "0";
JSONObject records = new JSONObject();
JSONObject device_info = new JSONObject();
WindowManager wm = (WindowManager) DocApplication.getContext().getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics displayMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(displayMetrics);
width = displayMetrics.widthPixels;
height = displayMetrics.heightPixels;
widthstr = String.valueOf(width);
heightstr = String.valueOf(height);
String device_model = Build.MODEL + " " + Build.VERSION.RELEASE;
device_info.put("app_version", userInfo.getFromPreferences("version"));
device_info.put("operating_system", getOsName());
device_info.put("device_resolution", widthstr + "*" + heightstr);
device_info.put("device_model", device_model);
device_info.put("device_manufacturer", Build.MANUFACTURER);
device_info.put("app_identifier", ResourceUtils.getResourceString(this, R.string.app_identifier_analytics));
JSONArray event = new JSONArray();
try {
Realm realm = SingleInstace.getInstace().getRealm();
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
try {
JSONObject eventobj = null;
RealmResults<DocquityLog> results = realm.where(DocquityLog.class).findAll();
results.load();
for (DocquityLog obj : results) {
JSONObject session_time = new JSONObject();
JSONObject location = new JSONObject();
eventobj = new JSONObject();
eventobj.put("event_name", obj.getEvent_name());
eventobj.put("product_type", obj.getProduct_type());
eventobj.put("product_type_id", obj.getProduct_type_id());
eventobj.put("session_id", obj.getSession_id());
eventobj.put("local_id", obj.getId());
eventobj.put("screen_name", obj.getScreen_name());
if (!Validation.isEmptyString(userInfo.getFromPreferences("user_id"))) {
eventobj.put("user_id", Integer.parseInt(userInfo.getFromPreferences("user_id")));
if (userInfo.isKeyExist("untrack_user_identifier")) {
eventobj.put("untrack_user_identifier", userInfo.getFromPreferences("untrack_user_identifier"));
userInfo.removeKey("untrack_user_identifier");
}
} else {
eventobj.put("user_id", 0);
eventobj.put("untrack_user_identifier", userInfo.getFromPreferences("untrack_user_identifier"));
}
session_time.put("start_time", obj.getStart_time());
session_time.put("end_time", obj.getEnd_time());
eventobj.put("session_time", session_time);
location.put("latitude", obj.getLatitude());
location.put("longitude", obj.getLongitude());
location.put("local", obj.getLocal());
location.put("time_zone", obj.getTime_zone());
eventobj.put("location", location);
event.put(eventobj);
}
} catch (Exception ex) {
LogEx.logExecption(TAG, "", ex);
}
}
});
} catch (Exception ex) {
LogEx.logExecption(TAG, "", ex);
} finally {
SingleInstace.getInstace().destroyRealm();
}
records.put("device_info", device_info);
records.put("event", event);
// Log.e(TAG, " records "+records.toString());
if (records != null && event.length() > 0) {
//apiAnalysticWork(records.toString());
ApiManager.getClientBasicAuthNewReactive(userInfo.getFromPreferences("user_auth_key"),
userInfo.getFromPreferences(userInfo.token_id),
ApiManager.GENRIC_API_VERSION_2, userInfo.getFromPreferences("version"),
GlobalSetting.Lng, "", ApiManager.DeviceType).getAnalysticRecord(records.toString())
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.computation())
.subscribe(searchResponse -> {
try {
int status = searchResponse.getStatus();
if (status == 1) {
// Log.e(TAG, "showSearchResult: success");
// delete work
try {
Realm realm = SingleInstace.getInstace().getRealm();
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
try {
RealmQuery q = realm.where(DocquityLog.class);
int x = 0;
for (Integer id : searchResponse.getAnalysticData().getSuccess_session_ids()) {
if (x != 0) {
q.or();
}
q = q.equalTo("id", id);
x++;
}
RealmResults<DocquityLog> filteredArticles = q.findAll();
filteredArticles.deleteAllFromRealm();
} catch (Exception ex) {
Log.e(TAG, " ex " + ex.getMessage());
Crashlytics.logException(ex);
}
}
});
} finally {
SingleInstace.getInstace().destroyRealm();
}
//RealmController.commitInput();
}
} catch (Exception ex) {
LogEx.logExecption(TAG, "", ex);
}
}, throwable -> LogEx.displayRetrofitError(TAG, throwable));
// Log.e(TAG, "jsonWorkAnalystic:reords "+records.toString() );
}
} catch (JSONException e) {
LogEx.logExecption(TAG, "JSONException", e);
} catch (Exception e) {
LogEx.logExecption(TAG, "OtherException", e);
}
}
/*public AnalysticsSubmit() {
super("AnalysticsSubmit");
}
#Override
public void onDestroy() {
// Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
}
#Override
protected void onHandleWork(#NonNull Intent intent) {
}
*/
public String getOsName() {
StringBuilder builder = new StringBuilder();
// builder.append("android : ").append(Build.VERSION.RELEASE);
Field[] fields = Build.VERSION_CODES.class.getFields();
for (Field field : fields) {
String fieldName = field.getName();
int fieldValue = -1;
try {
fieldValue = field.getInt(new Object());
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
if (fieldValue == Build.VERSION.SDK_INT) {
builder.append(fieldName);
}
}
return builder.toString();
}
}

How to register device token to smack 4.2?

Following is my code and I want to get push notification when my device is offline or app is killed.
When my app is background I want to get notify by XMPP ejabberd server
IQ Class
class MyCustomIQ extends IQ {
String token = SharedPreferenceManager.getValue(getApplicationContext(), "DEVICE_TOKEN");
protected MyCustomIQ() {
super("query", "urn:xmpp:registernoti");
}
#Override
protected IQChildElementXmlStringBuilder getIQChildElementBuilder(IQChildElementXmlStringBuilder xml) {
xml.rightAngleBracket();
xml.element("token", token);
xml.element("devicetpye", "android");
return xml;
}
}
On connected
#Override
public void connected(XMPPConnection connection) {
Log.e(TAG, "connected: ");
MyCustomIQ iq = new MyCustomIQ();
iq.setType(IQ.Type.set);
try {
abstractXMPPConnection.sendIqWithResponseCallback(iq, new StanzaListener() {
#Override
public void processStanza(Stanza packet) throws SmackException.NotConnectedException, InterruptedException {
Log.e(TAG, "processStanza: " + packet.toString());
}
});
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Try following code for register device token on xmpp server
Register token stanza
<iq to="YourServer" type="set">
<register xmlns="https://android.googleapis.com/gcm" >
<key>API_KEY</key>
</register>
</iq>
1) way for register token
public void registerTokenTomod_gcm(final String deviceToken){
IQ iq=new IQ("register","https://android.googleapis.com/gcm") {
#Override
protected IQChildElementXmlStringBuilder getIQChildElementBuilder(IQChildElementXmlStringBuilder xml) {
xml.attribute("key",deviceToken);
xml.setEmptyElement();
return xml;
}
};
iq.setType(IQ.Type.set);
iq.setTo(AppConstants.CHAT_HOSTNAME);
debugLog("getpushDicsoInfo send stanza:"+iq.toXML());
try {
if(connection.isSmEnabled()) {
debugLog("sm enabled");
try {
connection.addStanzaIdAcknowledgedListener(iq.getStanzaId(), new StanzaListener() {
#Override
public void processPacket(Stanza stanza) throws SmackException.NotConnectedException {
debugLog("SendMessage addStanzaIdAcknowledgedListener ::" + stanza.toXML());
if(registerXmppListener!=null){
registerXmppListener.onStanzaIdAcknowledgedReceived(stanza);
}
}
});
} catch (StreamManagementException.StreamManagementNotEnabledException e) {
e.printStackTrace();
}
}
connection.sendStanza(iq);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
2) way to register token
public void registerTokenToXmpp(String deviceId,String deviceName,String deviceToken){
DataForm xep0004 = new DataForm(DataForm.Type.submit);
FormField token = new FormField("token");
token.addValue(deviceToken);
FormField device_id = new FormField("device-id");
device_id.addValue(deviceId);
FormField device_name = new FormField("device-name");
device_name.addValue(deviceName);
xep0004.addField(token);
xep0004.addField(device_id);
xep0004.addField(device_name);
AdHocCommandData stanza = new AdHocCommandData();
stanza.setTo("android");
stanza.setType(IQ.Type.set);
stanza.setStanzaId("0043423");
stanza.setNode("register-push-gcm");
stanza.setAction(AdHocCommand.Action.execute);
stanza.setForm(xep0004);
stanza.setFrom(connection.getUser());
debugLog("getpushDicsoInfo send stanza:"+stanza.toXML());
try {
if(connection.isSmEnabled()) {
debugLog("sm enabled");
try {
connection.addStanzaIdAcknowledgedListener(stanza.getStanzaId(), new StanzaListener() {
#Override
public void processPacket(Stanza stanza) throws SmackException.NotConnectedException {
debugLog("SendMessage addStanzaIdAcknowledgedListener ::" + stanza.toXML());
if(registerXmppListener!=null){
registerXmppListener.onStanzaIdAcknowledgedReceived(stanza);
}
}
});
} catch (StreamManagementException.StreamManagementNotEnabledException e) {
e.printStackTrace();
}
}
connection.sendStanza(stanza);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
UnRegister device token from server
private void unregisterToken(){
String deviceid="3524940..."; //sony
String tokenstring="GHkd7Ro2qtMg:XPA91bflkgklDeg..."; // sony
DataForm xep0004 = new DataForm(DataForm.Type.submit);
FormField token = new FormField("token");
token.addValue(tokenstring);
FormField device_id = new FormField("device-id");
device_id.addValue(deviceid);
FormField device_name = new FormField("device-name");
// device_name.addValue(devicename);
xep0004.addField(token);
xep0004.addField(device_id);
xep0004.addField(device_name);
AdHocCommandData stanza = new AdHocCommandData();
stanza.setTo("android");
stanza.setType(IQ.Type.set);
stanza.setStanzaId("0043423");
stanza.setNode("register-push-gcm");
stanza.setAction(AdHocCommand.Action.execute);
stanza.setForm(xep0004);
stanza.setFrom(connection.getUser());
debugLog("getpushDicsoInfo send stanza:"+stanza.toXML());
try {
if(connection.isSmEnabled()) {
debugLog("sm enabled");
try {
connection.addStanzaIdAcknowledgedListener(stanza.getStanzaId(), new StanzaListener() {
#Override
public void processPacket(Stanza stanza) throws SmackException.NotConnectedException {
debugLog("SendMessage addStanzaIdAcknowledgedListener ::" + stanza.toXML());
if(registerXmppListener!=null){
registerXmppListener.onStanzaIdAcknowledgedReceived(stanza);
}
}
});
} catch (StreamManagementException.StreamManagementNotEnabledException e) {
e.printStackTrace();
}
}
connection.sendStanza(stanza);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
}

NetworkOnMainThreadException but Using AsyncTask

I coded a class which starts a http connection for getting the text of e.g. website.
I used AsyncTask but I got NetworkOnMainException. May u help me?
The class
public class getXMLData extends AsyncTask<String, Void, String> {
TextView _textview;
public getXMLData(TextView textview) {
_textview = textview;
}
protected String doInBackground(String... url)
{
String _text = "";
try {
try {
URL _url = new URL(url[0]);
HttpURLConnection con = (HttpURLConnection) _url.openConnection();
_text = readStream(con.getInputStream());
}
catch (Exception e) {
e.printStackTrace();
}
}
catch (Exception e) {
e.printStackTrace();
}
return _text;
}
protected void onPostExecute(String result)
{
_textview.setText(result.toCharArray(), 0, result.length());
}
private String readStream(java.io.InputStream in) {
java.io.BufferedReader reader = null;
String result = "";
reader = new BufferedReader(new InputStreamReader(in));
try {
while ((reader.readLine() != null)) {
result = result + reader.readLine();
}
}
catch (java.io.IOException i)
{
}
finally
{
try {
reader.close();
}
catch (java.io.IOException e) {
e.printStackTrace();
}
}
return result;
}
Here how I start the AsyncTask:
bu_aktualize.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
_getXMLData.doInBackground("http://www.google.de");
}
});
Thanks for your help.
You do not call doInBackground() yourself. Instead, you call execute() or executeOnExecutor() to start the AsyncTask.
You may wish to review the documentation for AsyncTask, which shows an example of setting up an AsyncTask, including a call to execute().

Calling a method inside thread in android

Hello below is a method where fileUpload method is called and after uploading files i want to delete the synchronized object and i did so. and now i have to reload the page by calling fillRecipients() method, what is does is it lists all the information from the database and shows in the listView. Since i have used the thread it doesnot allow me to put fillRecipeints inside the thread but i want it at line no 230[commented below as Line No 230] below
This is my Synchronize method:
public void synchronize(final String id){
dialog = ProgressDialog.show(ViewRecipients.this, "", "Uploading this file...", true);
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
//uploading.setText("uploading started.....");
//dialog.show();
}
});
mDbHelper.open();
Cursor cData = mDbHelper.fetchRecipientInfo(id);
for(cData.moveToFirst();!cData.isAfterLast();cData.moveToNext()){
String id = cData.getString(cData.getColumnIndex("fld_recipient_id"));
String info = cData.getString(cData.getColumnIndex("fld_info"));
String latitude = cData.getString(cData.getColumnIndex("fld_latitude"));
String longitude = cData.getString(cData.getColumnIndex("fld_longitude"));
ArrayList<String> imagesArray = new ArrayList<String>();
for (int i = 1; i <= 4; i++) {
String image = cData.getString(cData.getColumnIndex("fld_image_url" + i));
if (image != null) {
imagesArray.add(image);
}
}
try {
serverResponseCode = uploadFile(imagesArray, info, latitude, longitude, id);
if (serverResponseCode==200){
mDbHelper.deleteRecipientRecId(id);
//Line NO 230 here i want to add fillRecipients() method
}
dialog.dismiss();
} catch (IOException e) {
e.printStackTrace();
dialog.dismiss();
}
}
cData.close();
mDbHelper.close();
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(ViewRecipients.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
}
});
}
}
}).start();
}
This is my fillRecipeints() method:
private void fillRecipients(){
mCursor = mDbHelper.fetchAllRecipientsInfo();
if (mCursor==null){
System.out.println("empty cursor");
}
else{
String [] from = new String[]{MunchaDbAdapter.FLD_RECIPIENT_ID};
int [] to = new int[]{R.id.text1};
SimpleCursorAdapter recipient = new SimpleCursorAdapter(this, R.layout.recipient_show, mCursor, from, to);
setListAdapter(recipient);
}
}
can any body help me?
public void synchronize(final String id) {
new UploadAsync.execute();
}
//async class to do task in background and notify UI after completion of task in onPost()
class UploadAsync extends AsyncTask<Void, Void, Void>{
ProgressDialog dialog = null;
boolean isUploaded = false;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
ProgressDialog.show(ViewRecipients.this, "", "Uploading this file...", true);
}
#Override
protected Void doInBackground(Void... params) {
try{
mDbHelper.open();
Cursor cData = mDbHelper.fetchRecipientInfo(id);
for(cData.moveToFirst();!cData.isAfterLast();cData.moveToNext()){
String id = cData.getString(cData.getColumnIndex("fld_recipient_id"));
String info = cData.getString(cData.getColumnIndex("fld_info"));
String latitude = cData.getString(cData.getColumnIndex("fld_latitude"));
String longitude = cData.getString(cData.getColumnIndex("fld_longitude"));
ArrayList<String> imagesArray = new ArrayList<String>();
for (int i = 1; i <= 4; i++) {
String image = cData.getString(cData.getColumnIndex("fld_image_url" + i));
if (image != null) {
imagesArray.add(image);
}
}
try {
serverResponseCode = uploadFile(imagesArray, info, latitude, longitude, id);
if (serverResponseCode==200){
mDbHelper.deleteRecipientRecId(id);
isUploaded = true;
}
} catch (IOException e) {
e.printStackTrace();
}
}
cData.close();
mDbHelper.close();
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//close dialog
if(dialog != null && dialog.isShowing()){
dialog.dismiss();
}
if(isUploaded){
Toast.makeText(ViewRecipients.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
fillRecipients();
}
}
}
private void fillRecipients() {
mCursor = mDbHelper.fetchAllRecipientsInfo();
if (mCursor == null) {
System.out.println("empty cursor");
} else {
String[] from = new String[] { MunchaDbAdapter.FLD_RECIPIENT_ID };
int[] to = new int[] { R.id.text1 };
SimpleCursorAdapter recipient = new SimpleCursorAdapter(this,
R.layout.recipient_show, mCursor, from, to);
setListAdapter(recipient);
}
}

Categories