import com.github.nkzawa.emitter.Emitter;
private Emitter.Listener onNewMessage = new Emitter.Listener() {
#Override
public void call(final Object... args) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
String username;
String message;
try {
username = data.getString("username");
message = data.getString("message");
} catch (JSONExpextion e) {
return;
}
}
});
}
};
When I put in this code in my project, it said "Cannot resolve method
get Activity "
then, how can I deal with this problem?
You are calling getActivity() from inner class Emitter. So you should replace getActivity() with the name of your activity followed by .this. For example the name of your activity is MainActivity, then replace getActivity() with MainActivity.this
And your code would be like this:
private Emitter.Listener onNewMessage = new Emitter.Listener() {
#Override
public void call(final Object... args) {
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
String username;
String message;
try {
username = data.getString("username");
message = data.getString("message");
} catch (JSONExpextion e) {
return;
}
}
});
}
};
Related
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>
I have MyRepository that obtains a live feed from a server via a socket.
It provides its data to MyViewModel via a MutableLiveData object which can be observed from a Fragment.
To avoid wasting resources, I don't want MyRepository to be obtaining data from the server when there are no observers.
I'd like to know how to monitor MyRepository's MutableLiveData, so if there are no observers then MyRepository can stop retrieving data from the server. Similarly, if an observer is added, then data retrieval can (re)start.
Currently, I'm just using a basic Thread (see the createObserversMonitorThread() method) as the monitor:
public class MyRepository {
private static final String TAG = MyRepository.class.getSimpleName();
private MutableLiveData<String> mutableLiveData;
private Socket mSocket = null;
public MyRepository(Application application) {
mutableLiveData = new MutableLiveData<>();
createSocket();
createObserversMonitorThread();
}
private void createObserversMonitorThread() {
Thread thread = new Thread() {
#Override
public void run() {
try {
while (isAlive()) {
if (mutableLiveData.hasActiveObservers()) {
// We have observers, so connect to the server.
if (!mSocket.connected()) {
mSocket.connect();
}
}
else {
// We don't have observers, so disconnect from the server.
if (mSocket.connected()) {
mSocket.disconnect();
}
}
// Wait until next loop.
Thread.sleep(1000);
}
}
catch(Exception e) {
Log.e(TAG, "Exception", e);
}
}
};
thread.setName("MutableLiveData Observers Monitor");
thread.setPriority(1);
thread.setDaemon(true);
thread.start();
}
public LiveData<String> getMutableLiveData() {
return mutableLiveData;
}
/**
* This method posts retrieved data to mutableLiveData.
*/
private void createSocket() {
try {
mSocket = IO.socket(Constants.SERVER_URL);
mSocket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.d(TAG, "Connected.");
}
}).on(Socket.EVENT_CONNECT_ERROR, new Emitter.Listener() {
#Override
public void call(Object... args) {
if (args[0] instanceof Exception) {
Log.e(TAG, "Connect error: ", (Exception)args[0]);
}
else {
Log.e(TAG, "Connect error: " + args[0]);
}
}
}).on(Socket.EVENT_RECONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.d(TAG, "Reconnected.");
}
}).on(Socket.EVENT_RECONNECT_ERROR, new Emitter.Listener() {
#Override
public void call(Object... args) {
if (args[0] instanceof Exception) {
Log.e(TAG, "Reconnect error: ", (Exception)args[0]);
}
else {
Log.e(TAG, "Reconnect error: " + args[0]);
}
}
}).on(Socket.EVENT_MESSAGE, new Emitter.Listener() {
#Override
public void call(Object... args) {
//Log.d(TAG, "Data received.");
String s = (String) args[0];
mutableLiveData.postValue(s);
}
}).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.d(TAG, "Disconnected.");
}
}).on(Socket.EVENT_ERROR, new Emitter.Listener() {
#Override
public void call(Object... args) {
if (args[0] instanceof Exception) {
Log.e(TAG, "Error: ", (Exception)args[0]);
}
else {
Log.e(TAG, "Error: " + args[0]);
}
}
});
}
catch(Exception e) {
Log.e(TAG, "Could not create socket", e);
}
}
}
It works, but is there a better way?
UPDATE
Solution, thanks to EpicPandaForce's answer:
public class MyRepository {
private static final String TAG = MyRepository.class.getSimpleName();
private MutableLiveData<String> mutableLiveData;
private Socket mSocket = null;
public MyRepository(Application application) {
createSocket();
mutableLiveData = new MutableLiveData<String>() {
#Override
protected void onActive() {
super.onActive();
// Connect to server. This will (re)start data being posted on mutableLiveData.
if (!mSocket.connected()) {
mSocket.connect();
}
}
#Override
protected void onInactive() {
super.onInactive();
// Disconnect from server. This will stop data being posted on mutableLiveData.
if (mSocket.connected()) {
mSocket.disconnect();
}
}
};
}
public LiveData<String> getMutableLiveData() {
return mutableLiveData;
}
/**
* This method posts retrieved data to mutableLiveData.
*/
private void createSocket() {
// Same code as before.
}
}
You can use extends LiveData<T> or extends MutableLiveData<T> to get ahold of onActive() callback where you are notified if you have at least 1 active observer, and onInactive() callback when you went from 1 to 0 active observers.
That way you don't even need to ask for hasActiveObservers().
This question already has answers here:
How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?
(17 answers)
Closed 5 years ago.
How to catch moment when AsyncTask is finished?
I have ProfileUpdate class which extends AsyncTask, and from another activity I calling this method and after I need update my data. How to know that asynctask finished? My asynctask method in another class and not in activity class!!!
this is my onRefresh method in the activity:
#Override
public void onRefresh() {
if (!AlertView.isInternetAvailable(getContext())) {
swipeLayout.setRefreshing(false);
Toast.makeText(getContext(), Messages.CONNECTION_ERROR + ": " + Messages.NO_INTERNET, Toast.LENGTH_SHORT).show();
} else {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
new UpdateProfile(getActivity(), swipeLayout, sharedPreferences.getString(Constants.TOKEN, ""), user.getIin()).execute(Urls.GET_USER);
}
});
profileDefaults();
}
}
and here my AsyncTask method:
public class UpdateProfile extends AsyncTask <String, Void, String> {
private Activity activity;
private SwipeRefreshLayout swipeRefreshLayout;
private String token;
private String userIin;
private SharedPreferences sharedPreferences;
public UpdateProfile(Activity activity, SwipeRefreshLayout swipeRefreshLayout, String token, String userIin) {
this.activity = activity;
this.swipeRefreshLayout = swipeRefreshLayout;
this.token = token;
this.userIin = userIin;
sharedPreferences = this.activity.getSharedPreferences(Constants.PROJECT, Context.MODE_PRIVATE);
}
#Override
protected String doInBackground(String... params) {
URL url = null;
try {
url = new URL(params[0]);
try {
OkHttpClient okHttpClient = new OkHttpClient();
RequestBody body = new FormBody.Builder()
.add("iin", userIin)
.build();
Request request = new Request.Builder()
.url(url)
.addHeader(Constants.AUTH_TOKEN, token)
.post(body)
.build();
Response responses = null;
try {
responses = okHttpClient.newCall(request).execute();
} catch (Exception e) {
AlertView.showAlertView(activity, Messages.CONNECTION_ERROR, Messages.NO_INTERNET, Messages.OK);
}
assert responses != null;
return responses.body().string();
} catch (Exception e) {
AlertView.showAlertView(activity, Messages.CONNECTION_ERROR, Messages.NO_INTERNET, Messages.OK);
}
} catch (Exception e) {
AlertView.showAlertView(activity, Messages.CONNECTION_ERROR, Messages.NO_INTERNET, Messages.OK);
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject jsonObject = new JSONObject(s);
int code = Integer.valueOf(jsonObject.getString(Constants.CODE));
if (code == Codes.OK) {
Toast.makeText(activity, "Данные обновлены", Toast.LENGTH_SHORT).show();
String userHeader = jsonObject.getString("user");
JSONObject userInfo = new JSONObject(userHeader);
String mobilePhone = userInfo.getString(SingletonConstants.MOBILE_PHONE);
Boolean isActive = userInfo.getBoolean(SingletonConstants.IS_ACTIVE);
Boolean signedAgreement = userInfo.getBoolean(SingletonConstants.SIGNED_AGREEMENT);
Boolean esfEntered = userInfo.getBoolean(SingletonConstants.ESF_ENTERED);
String address = userInfo.getString(SingletonConstants.ADDRESS);
String iin = userInfo.getString(SingletonConstants.IIN);
String certExpDate = userInfo.getString(SingletonConstants.CERT_EXP_DATE);
String firstName = userInfo.getString(SingletonConstants.FIRST_NAME);
String middleName = userInfo.getString(SingletonConstants.MIDDLE_NAME);
String workPhone = userInfo.getString(SingletonConstants.WORK_PHONE);
String secondName = userInfo.getString(SingletonConstants.SECOND_NAME);
String avatarUrl = userInfo.getString(SingletonConstants.AVATAR_URL);;
String secondEmail = userInfo.getString(SingletonConstants.SECOND_EMAIL);
String email = userInfo.getString(SingletonConstants.EMAIL);
User newUser = new User(mobilePhone, isActive, signedAgreement, esfEntered, address, iin, certExpDate, firstName, middleName, workPhone, secondName, avatarUrl, secondEmail, email);
Gson gson = new Gson ();
String userGson = gson.toJson (newUser);
sharedPreferences.edit().putString(SingletonConstants.USER, userGson).apply();
swipeRefreshLayout.setRefreshing(false);
} else {
AlertView.showAlertView(activity, Messages.ERROR, jsonObject.getString(Constants.MESSAGE), Messages.OK);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
How I can call profileDefaults()? It's into my activity. And I need to call it after onPostExecute!
A cleaner way to do it is to use interfaces as listeners.
Create this interface:
public interface OnAsyncFinished{
void onAsyncFinished(Object o);
}
Add the interface as a parameter in your AsyncTaskClass constructor:
private OnAsyncFinished onAsyncFinished;
public UpdateProfile(..., OnAsyncFinished onAsyncFinished) {
...
this.onAsyncFinished = onAsyncFinished;
}
...
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
onAsyncFinished.onAsyncFinished(s); //This will notifiy the method on main activity, and you can now resume the work there
...
}
Implement the interface in your main activity:
public MainActivity extends Activity implements OnAsyncFinished {
#Override
public void onAsyncFinished(Object o) {
//This will get called after onPostExecute, do what u want with the object you got from onPostExecute, json or string in ur example
profileDefaults(); //call ur function
}
}
EDIT:
When creating the async task in your main activity pass this in the constructor likeso:
#Override
public void run() {
new UpdateProfile(..., this).execute(Urls.GET_USER);
}
This is likely a basic Java question. All in same activity, I declare a String[] data, later update it succesfully, but when I attempt to set a textview to the updated data[1] from the calling funtion that updated data[1] - nothing showing. Here is the stripped down code.
public class MyClass extends AppCompatActivity {
String[] data = new String[4];
public void populateGrid() {}
getIndexData(indices);
final TextView test = (TextView) findViewById(R.id.textView0B);
test.post(new Runnable() {
#Override
public void run() {
test.setText(data[1]);
}
});
public void getIndexData(final String[] indices){
//lots of work accomplished, data[1] is updated, Log.d() logs good!
// Tried passing data[] as a parameter from populateGrid(), but that didn't work.
// Tried returning data[] to populateGrid(), also didn't work.
}
}
What is the proper method for accomplishing this task?
As requested, getIndexData()
public void getIndexData(final String indices){
mOkHttpClient = new OkHttpClient();
HttpUrl reqUrl = HttpUrl.parse("http://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=" +
indices +
"&outputsize=compact&apikey=" +
apiKey);
Request request = new Request.Builder().url(reqUrl).build();
mOkHttpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
// Show user error message if not connected to internet, et. al.
runOnUiThread(new Runnable() {
#Override
public void run() {
Context context = getApplicationContext();
CharSequence text = getResources().getString(R.string.Toast_1);
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
});
}
#Override
public void onResponse(Call call, Response response) throws IOException {
int j = 0;
String responseBody = response.body().string();
if (responseBody.contains("\"Error Message\"")) {
data[j] = "No Data";
data[j+1] = "No Data";
data[j+2] = "No Data";
data[j+3] = "No Data";
} else { // Extract data points from json object.
try {
JSONObject baseObject = new JSONObject(responseBody);
JSONObject timeSeriesObj = baseObject.optJSONObject("Time Series (Daily)");
Iterator<String> iterator = timeSeriesObj.keys();
List<Map<String, String>> tickerData = new ArrayList<Map<String, String>>();
while (iterator.hasNext()) {
String key = iterator.next();
if (key != null) {
HashMap<String, String> m = new HashMap<String, String>();
JSONObject finalObj = timeSeriesObj.optJSONObject(key);
m.put("1. open", finalObj.optString("1. open"));
m.put("2. high", finalObj.optString("2. high"));
m.put("3. low", finalObj.optString("3. low"));
m.put("4. close", finalObj.optString("4. close"));
m.put("5. volume", finalObj.optString("5. volume"));
tickerData.add(m);
}
}
int k = 0;
String str = tickerData.get(0).toString();
data[k] = StringUtils.substringBetween(str, "open=", ", ");
//Log.d("data[0]= ", data[0]);
data[k+1] = StringUtils.substringBetween(str, "close=", ", ");
Log.d("data[1]", data[1]); // logs 2431.7700
data[k+2] = "";
data[k+3] = "";
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
}
It would be something like this:
public class MyClass extends AppCompatActivity {
String[] data = new String[4];
public void populateGrid() {
getIndexData(indices);
}
public void getIndexData(final String indices) {
// set up http request
mOkHttpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
// ...
}
#Override
public void onResponse(Call call, Response response) throws IOException {
// process the response, populate data etc.
final TextView test = (TextView) findViewById(R.id.textView0B);
test.post(new Runnable() {
#Override
public void run() {
test.setText(data[1]);
}
});
}
}
}
}
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.