AsyncHttpPost force close when there is not internet - android

I used fragment in my application and when there is not internet app getting force close . I don't know what can I do . please help me
this code works perfect but when internet lost the application get error and force close
i use method to check internet by ping but it makes my app too slow
public static void get_detail(final int pages){
MainActivity.logo11.setImageResource(R.drawable.loading);
AsyncHttpPost post = new AsyncHttpPost(
"domain"
);
post.setTimeout(30000);
MultipartFormDataBody body = new MultipartFormDataBody();
body.addStringPart("City",MainActivity.sp.getString("City",null));
body.addStringPart("Cate","all");
body.addStringPart("Page", String.valueOf(pages));
post.setBody(body);
AsyncHttpClient.getDefaultInstance().executeString(post, new AsyncHttpClient.StringCallback() {
#Override
public void onCompleted(final Exception e, AsyncHttpResponse source, final String result) {
if(e != null){
MainActivity.activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.activity,"network error",Toast.LENGTH_LONG).show();
refresh.setRefreshing(false);
e.printStackTrace();
}
});
}
if(!result.equals("")){
MainActivity.activity.runOnUiThread(new Runnable() {
#Override
public void run() {
MainActivity.logo11.setImageResource(R.drawable.logo);
if(page==0){
hash_all.clear();
}
items.clone();
try {
JSONArray jsonArray = new JSONArray(result);
for (int i = 0 ;i<jsonArray.length();i++){
JSONObject object = jsonArray.getJSONObject(i);
HashMap<String , Object> hash_add = new HashMap<String, Object>();
hash_add.put("ID",object.getString("ID"));
hash_add.put("Username",object.getString("Username"));
hash_add.put("Title",object.getString("Title"));
hash_add.put("Descript",object.getString("Descript"));
hash_all.add(hash_add);
items = new String[hash_all.size()];
}
ad.notifyDataSetChanged();
refresh.setRefreshing(false);
}catch (Exception e){
e.printStackTrace();
}
}
});
}else {
Toast.makeText(MainActivity.activity,"error",Toast.LENGTH_LONG).show();
}
}
});
}

Related

Android Asynctask arraylist always returns 0

I have an activity where I have a URL and with the Volley Library , I am fetching the JSON data in an ArrayList of Objects of Model Class DmIncomingTest. Now, I pas URL to the checkLiveQuiz() method, even after getting data from server and adding it to the ArrayList, the size of ArrayList is always 0. I am sharing the code here:
private List<DmInComingTest> inComingTestList;
setContentView(R.layout.activity_no_live_quiz);
......
new MyAsyncTask().execute();
}
private class MyAsyncTask extends AsyncTask<Void, Void, Void> {
private Context context;
#Override
protected void onPreExecute() {
inComingTestList= new ArrayList<DmInComingTest>();
// dialog = ProgressDialog.show(NoLiveQuiz.this, "Please wait..", "Doing stuff..", true);
}
#Override
protected Void doInBackground(Void... voids) {
checkLiveQuiz();
return null;
}
#Override
protected void onPostExecute(Void result) {
// Toast.makeText(NoLiveQuiz.this,"Size of inComingTestList :"+inComingTestList.size(),Toast.LENGTH_LONG).show();
if(inComingTestList.size()==0)
{
Toast.makeText(NoLiveQuiz.this,"Size of inComingTestList :"+inComingTestList.size(),Toast.LENGTH_LONG).show();
}
else
{
startActivity(new Intent(NoLiveQuiz.this,LiveQuiz.class));
}
// dialog.dismiss();
}
}
public void checkLiveQuiz()
{
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.show();
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url_live_quiz, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
DmInComingTest inComingTest = new DmInComingTest();
inComingTest.setTitle(jsonObject.getString("title"));
inComingTest.setTotal_questions(jsonObject.getString("qcount"));
inComingTest.setDated(jsonObject.getString("date_format(dated,'%d.%m.%Y')"));
inComingTest.setStartTime(jsonObject.getString("starttime"));
inComingTest.setEndTime(jsonObject.getString("endtime"));
inComingTest.setDuration(jsonObject.getInt("duration"));
inComingTest.setMaxMarks(jsonObject.getInt("maxmarks"));
if(validateTest(jsonObject.getString("date_format(dated,'%d.%m.%Y')"),jsonObject.getString("starttime"),jsonObject.getString("endtime"),jsonObject.getInt("duration")))
{
inComingTestList.add(inComingTest);
Toast.makeText(NoLiveQuiz.this,"Test Added: "+ inComingTestList.size(),Toast.LENGTH_LONG).show();
// flag=1;
// Toast.makeText(MainActivity.this,"Flag Inner="+flag,Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
progressDialog.dismiss();
}
}
// adapter.notifyDataSetChanged();
progressDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
// progressDialog.dismiss();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
private boolean validateTest(String testDate, String startTime, String endTime, int duration)
{
Date oldDate, newDate,newDate1;
String oldTime,newTime,newTime1;
long diff=0;
long oldLong=0;
long newLong=0;
long newLong1=0;
SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy, HH:mm:ss");
formatter.setLenient(false);
Calendar c = Calendar.getInstance();
oldTime=formatter.format(c.getTime());
// Toast.makeText(MainActivity.this, ""+oldTime, Toast.LENGTH_SHORT).show();
newTime=testDate +", "+startTime+":00";
newTime1=testDate +", "+endTime+":00";
// Toast.makeText(MainActivity.this, ""+newTime, Toast.LENGTH_SHORT).show();
try {
oldDate = formatter.parse(oldTime);
newDate = formatter.parse(newTime);
newDate1=formatter.parse(newTime1);
oldLong = oldDate.getTime();
newLong = newDate.getTime();
newLong1=newDate1.getTime();
diff = newLong - oldLong;
} catch (ParseException e) {
e.printStackTrace();
}
//long timer= (long) Long.parseLong(String.valueOf(diff));
//Toast.makeText(IncomingActivity.this, ""+timer, Toast.LENGTH_SHORT).show();
if(oldLong>newLong && oldLong<newLong1)
{
return true;
}
else
return false;
}

Android Socket.io emits twice instead of once?

I'm using android socket.io but the problem is that emit event runs twice instead of once , i mean that i wrote just one emit code in the onCreate method , but it sends two request for the server ?
I searched alot but not found anything .
I use node js in the backend ,and my code has not any problems .
Is there a bug in socket.io for android ?
Here is my code :
SocketManager.getInstance().connect();
// Creating Bids
final Handler mHandler04 = new Handler(Looper.getMainLooper());
mHandler04.post(new Runnable() {
#Override
public void run() {
SocketManager.getInstance().getSocket().emit("allc", "some");
SocketManager.getInstance().getSocket().on("allcRes", new Emitter.Listener() {
#Override
public void call(final Object... args) {
g.context.runOnUiThread(new Runnable() {
#Override
public void run() {
JSONArray jsonArray = (JSONArray) args[0];
arrayComps.clear();
Log.d(TAG, "run: " + jsonArray);
try {
for (int i = 0; i < jsonArray.length(); i++) {
createView(jsonArray.getJSONObject(i).getString("title"), jsonArray.getJSONObject(i).getString("realprice"), jsonArray.getJSONObject(i).getString("id"), jsonArray.getJSONObject(i).getString("starttime"), jsonArray.getJSONObject(i).getString("img"));
CustomViewCompetition css = (CustomViewCompetition) LinearLayoutItemHolder.getChildAt(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
});
final Handler bidsupdateHandler = new Handler(Looper.getMainLooper());
bidsupdateHandler.post(new Runnable() {
#Override
public void run() {
SocketManager.getInstance().getSocket().on("bidsupdate", new Emitter.Listener() {
#Override
public void call(final Object... args) {
final JSONArray jsonArray = (JSONArray) args[0];
g.context.runOnUiThread(new Runnable() {
#Override
public void run() {
Log.d(TAG, "run in bidsupdate");
try {
for (int i = 0; i < jsonArray.length(); i++) {
bidsMap.put(jsonArray.getJSONObject(i).getInt("key"), jsonArray.getJSONObject(i).getInt("value"));
}
for (int i = 0; i < LinearLayoutItemHolder.getChildCount(); i++) {
CustomViewCompetition cs = (CustomViewCompetition) LinearLayoutItemHolder.getChildAt(i);
Log.d(TAG, "run in cs " + cs.txtCsRealPrice.getText());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
});
the Problem is when i get the cs.txtCsTitle.getText() it is just showing me one of them
Add this line:
SocketManager.getInstance().getSocket().emit("allc", "some");
just after:
SocketManager.getInstance().connect();
So your code will be like
SocketManager.getInstance().connect();
SocketManager.getInstance().getSocket().emit("allc", "some");
And remove from where you are already using in handler. Also you dont need handlers why you are using handlers? Create your listener and emit your subscription out of handlers it needs to be created or subscribed once. On creation of emitter listener pass views if you need to update any view. then update the views here you may need runnable to update UI on uiThread.
Create Class as follows:
public class YourListener implements Emitter.Listener
{
private yourView view;
public YourListener (View view)
{
this.view = view;
}
#Override
public void call(Object... args)
{
// do your work here
}
}
and replace below code :
SocketManager.getInstance().getSocket().on("allcRes", new Emitter.Listener() {
#Override
public void call(final Object... args) {
g.context.runOnUiThread(new Runnable() {
#Override
public void run() {
JSONArray jsonArray = (JSONArray) args[0];
arrayComps.clear();
Log.d(TAG, "run: " + jsonArray);
try {
for (int i = 0; i < jsonArray.length(); i++) {
createView(jsonArray.getJSONObject(i).getString("title"), jsonArray.getJSONObject(i).getString("realprice"), jsonArray.getJSONObject(i).getString("id"), jsonArray.getJSONObject(i).getString("starttime"), jsonArray.getJSONObject(i).getString("img"));
CustomViewCompetition css = (CustomViewCompetition) LinearLayoutItemHolder.getChildAt(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
with:
SocketManager.getInstance().getSocket().on("your_subscription", new YourListener (yourView));

database connection with asynctask error

Hi I'm beginner at android so I hope that you would help me in details
I made connection to MySQL database with AsyncTask it's all good it connects well and I get my data from the database but the thing is when I turn off my database (database is on wamp) my app force closes and it gives this error:java.util.concurrent.timeoutexception
I will put the AsyncTask codes below
private void get_banners(final int pages) {
AsyncHttpPost post = new AsyncHttpPost("http://192.168.1.102/soton/new.php");
post.setTimeout(5000);
MultipartFormDataBody body = new MultipartFormDataBody();
body.addStringPart("City", MainActivity.sp.getString("City", ""));
body.addStringPart("Page", String.valueOf(pages));
body.addStringPart("Cate", "all");
post.setBody(body);
AsyncHttpClient.getDefaultInstance().executeString(post, new AsyncHttpClient.StringCallback() {
#Override
public void onCompleted(final Exception e, AsyncHttpResponse source, final String result) {
if (e != null) {
MainActivity.activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.activity, e.toString(), Toast.LENGTH_LONG).show();
e.printStackTrace();
mSwipeRefreshLayout.setRefreshing(false);
}
});
}
if (!result.equals("")) {
MainActivity.activity.runOnUiThread(new Runnable() {
#Override
public void run() {
//you can toast the result here
//Toast.makeText(MainActivity.activity, result,Toast.LENGTH_LONG).show();
if (page == 0) {
hash_all.clear();
}
items.clone();
try {
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
HashMap<String, Object> hash_add = new HashMap<>();
hash_add.put("ID", object.getString("ID"));
hash_add.put("Username", object.getString("Username"));
hash_add.put("Title", object.getString("Title"));
hash_add.put("Description", object.getString("Description"));
hash_add.put("Price", object.getString("Price"));
hash_add.put("Tell", object.getString("Tell"));
hash_add.put("Email", object.getString("Email"));
hash_add.put("City", object.getString("City"));
hash_add.put("Cate", object.getString("Cate"));
hash_add.put("Img1", object.getString("Img1"));
hash_add.put("Img2", object.getString("Img2"));
hash_add.put("Img3", object.getString("Img3"));
hash_add.put("Date", object.getString("Date"));
hash_all.add(hash_add);
items = new String[hash_all.size()];
}
ad.notifyDataSetChanged();
mSwipeRefreshLayout.setRefreshing(false);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
else {
Toast.makeText(MainActivity.activity,result,Toast.LENGTH_LONG).show();
}
}
});
}
Update: Stack Trace
FATAL EXCEPTION: AsyncServer
Process: com.morteza.newproject, PID: 3211
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at com.morteza.newproject.Frag_banners_all$3.onCompleted(Frag_banners_all.java:145)
at com.morteza.newproject.Frag_banners_all$3.onCompleted(Frag_banners_all.java:130)
at com.koushikdutta.async.http.AsyncHttpClient.invokeWithAffinity(AsyncHttpClient.java:527)
at com.koushikdutta.async.http.AsyncHttpClient.access$800(AsyncHttpClient.java:51)
at com.koushikdutta.async.http.AsyncHttpClient$7.run(AsyncHttpClient.java:534)
at com.koushikdutta.async.AsyncServer.lockAndRunQueue(AsyncServer.java:740)
at com.koushikdutta.async.AsyncServer.runLoop(AsyncServer.java:758)
at com.koushikdutta.async.AsyncServer.run(AsyncServer.java:658)
at com.koushikdutta.async.AsyncServer.access$800(AsyncServer.java:44)
at com.koushikdutta.async.AsyncServer$14.run(AsyncServer.java:600)
W/System.err: java.util.concurrent.TimeoutException
W/System.err: at com.koushikdutta.async.http.AsyncHttpClient$2.run(AsyncHttpClient.java:246)
W/System.err: at com.koushikdutta.async.AsyncServer.lockAndRunQueue(AsyncServer.java:740)
W/System.err: at com.koushikdutta.async.AsyncServer.runLoop(AsyncServer.java:758)
W/System.err: at com.koushikdutta.async.AsyncServer.run(AsyncServer.java:658)
W/System.err: at com.koushikdutta.async.AsyncServer.access$800(AsyncServer.java:44)
W/System.err: at com.koushikdutta.async.AsyncServer$14.run(AsyncServer.java:600)
Application terminated.
Problem soved i solved it by adding only an else to the code the currect code is below
private void get_banners(final int pages) {
AsyncHttpPost post = new AsyncHttpPost("http://192.168.1.102/soton/new.php");
post.setTimeout(5000);
MultipartFormDataBody body = new MultipartFormDataBody();
body.addStringPart("City", MainActivity.sp.getString("City", ""));
body.addStringPart("Page", String.valueOf(pages));
body.addStringPart("Cate", "all");
post.setBody(body);
try {
AsyncHttpClient.getDefaultInstance().executeString(post, new AsyncHttpClient.StringCallback() {
#Override
public void onCompleted(final Exception e, AsyncHttpResponse source, final String result) {
if (e != null) {
MainActivity.activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.activity, "server is offline", Toast.LENGTH_LONG).show();
e.printStackTrace();
mSwipeRefreshLayout.setRefreshing(false);
}
});
}
//this is the answer
else {
if (!result.equals("")) {
MainActivity.activity.runOnUiThread(new Runnable() {
#Override
public void run() {
//you can toast the result here
//Toast.makeText(MainActivity.activity, result,Toast.LENGTH_LONG).show();
if (page == 0) {
hash_all.clear();
}
items.clone();
try {
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
HashMap<String, Object> hash_add = new HashMap<>();
hash_add.put("ID", object.getString("ID"));
hash_add.put("Username", object.getString("Username"));
hash_add.put("Title", object.getString("Title"));
hash_add.put("Description", object.getString("Description"));
hash_add.put("Price", object.getString("Price"));
hash_add.put("Tell", object.getString("Tell"));
hash_add.put("Email", object.getString("Email"));
hash_add.put("City", object.getString("City"));
hash_add.put("Cate", object.getString("Cate"));
hash_add.put("Img1", object.getString("Img1"));
hash_add.put("Img2", object.getString("Img2"));
hash_add.put("Img3", object.getString("Img3"));
hash_add.put("Date", object.getString("Date"));
hash_all.add(hash_add);
items = new String[hash_all.size()];
}
ad.notifyDataSetChanged();
mSwipeRefreshLayout.setRefreshing(false);
} catch (Exception e) {
e.printStackTrace();
}
}
});
} else {
Toast.makeText(MainActivity.activity, result, Toast.LENGTH_LONG).show();
}
}
}
});
}catch (Exception e){
e.printStackTrace();
}
}

View.Visible working fine in Marshmallow but not working on Kikat

View.Visible is working fine the above version 5.0 in android but not working on Kitkat version. Not getting actual problem, Am searched a lot but not getting solution following is my code. Thank you in advance
public class mainActivity extends AppCompatActivity implements View.OnClickListener {
Button button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stb_commands);
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(this);
button1.setVisibility(View.GONE);
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button1:
HashMap data = new HashMap();
new mainActivity.AsyncTaskGenre(data).execute();
break;
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(mainActivity.this);
pDialog.setMessage("Loading...");
pDialog.show();
}
#Override
protected String doInBackground(Void... params) {
String request = "http://";
try {
JSONObject json = jsonParser.makeHttpRequest(request, "POST",data);
return json.toString();
} catch (Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
pDialog.dismiss();
Log.d("RESULT ",""+s);
if (s != null) {
try {
JSONObject jsonObject = new JSONObject(s);
String error = jsonObject.get("error").toString();
Log.d("RESULT", " " +error);
if (error.equals("false"))
{
button1.setVisibility(View.VISIBLE);
}
else
{
Toast.makeText(getApplicationContext(),"not found...!",Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
else{
Toast.makeText(getApplicationContext(),"check connection...!",Toast.LENGTH_LONG).show();
}
}
}
At first Compare your String Value Properly
Code Rectify
if (error.equals("false")) // Why you set == ?
{
button1.setVisibility(View.VISIBLE);
}
else
{
Toast.makeText(getApplicationContext(),"not found...!",Toast.LENGTH_SHORT).show();
}
FYI
JSON Response is
{"error":false,"1":{"id":6,"name":"Prash"}}
String getError=jsonObject .getString("error").toString();
Now do your code
if (error.equals("false"))
{
button1.setVisibility(View.VISIBLE);
}
In java you can use equels instead of ==
if (error.equalsIgnoreCase("false"))
{
button1.setVisibility(View.VISIBLE);
}
else
{
Toast.makeText(getApplicationContext(),"not found...!",Toast.LENGTH_SHORT).show();
}
I found the problem there is parsing issue thank you guys.
JSONObject jsonObject = new JSONObject(s);
String error = jsonObject.get("error").toString();
Log.d("RESULT", " " +error);
if (error.equals("false"))
{
Iterator keys = jsonObject.keys();
JSONObject currentDynamicValue;
int i=0;
while (keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String) keys.next();
if (!currentDynamicKey.equals("error")) {
// get the value of the dynamic key
currentDynamicValue = jsonObject.getJSONObject(currentDynamicKey);
list.put(i, currentDynamicValue.get("command_id").toString());
i++;
final String command_id = currentDynamicValue.get("command_id").toString();
if(command_id.equals("0"))
{
button1.setVisibility(View.VISIBLE);
}
else{
Toast.makeText(getApplicationContext(), "Command not Found..!" , Toast.LENGTH_SHORT).show();
}
}
}
Attach debugger inside onPostExecution() method, and handle your conditions according to the response. as there must be something wrong in "jsonObject.get("error").toString()"this.SO debug and handel your response you can.There is nothing wrong with setVisiblity(View.VISIBLE).
rest your code seems to be fine. Give it a try and then reply.

best way to run a method inside service without disturbing Main UI thread

I have a method which fetches the contacts from phone and send this to the php server for processing then it will return data so that it will update in the sql lite DB. I need to run this method continuously on background. I am using Volley for network operation. I am using Handler inside service to run this method. The problem is i am seen too many skipping frames and app is very slow and stucks. I want to run this method without disturbing the main thread. The service code is mentioned below.
public class serv extends Service {
ArrayList<String> aa= new ArrayList<>();
ArrayList<String> bb= new ArrayList<>();
JSONObject JSONimdb;
JSONObject EverythingJSON;
ArrayList<mobstat> musers = new ArrayList<mobstat>();
private RequestQueue requestQueue;
String l;
private static Timer timer = new Timer();
#Override
public void onTaskRemoved(Intent rootIntent) {
Log.e("Shiva","Service Killed");
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
//nonstop1();
threadcheck();
return Service.START_STICKY;
}
private void _startService()
{
long UPDATE_INTERVAL = 5 * 1000;
timer.scheduleAtFixedRate(
new TimerTask()
{
public void run()
{
try
{
getNumber(serv.this.getContentResolver());
} catch (JSONException e)
{
e.printStackTrace();
}
}
}, 1000, UPDATE_INTERVAL);
}
private void nonstop1()
{
final Handler handlera = new Handler();
Runnable updatea = new Runnable()
{
#Override
public void run()
{
try {
getNumber(serv.this.getContentResolver());
} catch (JSONException e) {
e.printStackTrace();
}
handlera.postDelayed(this , 1000);
}
};
handlera.postDelayed(updatea, 10);
}
private void threadcheck()
{
new Thread() {
public void run() {
try {
Log.e("Shiva","Threadcheck");
getNumber(serv.this.getContentResolver());
} catch (JSONException e) {
e.printStackTrace();
}
}
}.start();
}
#Override
public void onDestroy()
{
super.onDestroy();
// Intent broadcatIntent = new Intent("com.statmob.findnum");
//sendBroadcast(broadcatIntent);
//stoptimertask();
//nonstop1();
threadcheck();
}
public void getNumber(ContentResolver cr) throws JSONException
{
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (phoneNumber.length()>=10)
{
l = phoneNumber.substring(phoneNumber.length()-10);
aa.add(l);
bb.add(name);}
}
phones.close();
JSONimdb = new JSONObject();
for (int i = 0; i < aa.size(); i++)
{
try
{
JSONimdb.put(bb.get(i), aa.get(i));
} catch (JSONException e)
{
e.printStackTrace();
}
}
EverythingJSON = new JSONObject();
try
{
EverythingJSON.put("imdblist", JSONimdb);
} catch (JSONException e)
{
e.printStackTrace();
}
StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://xxxxxxxx/cont.php",
new Response.Listener<String>()
{
#Override
public void onResponse(String s)
{
if (s != null)
{
parseJSONresponse(s);
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Log.e("Shiva",""+error);
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError
{
Map<String, String> params = new Hashtable<String, String>();
params.put("arr", EverythingJSON.toString());
return params;
}
};
int socketTimeout = 50000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
if(requestQueue==null)
{
requestQueue = Volley.newRequestQueue(serv.this);}
stringRequest.setRetryPolicy(policy);
requestQueue.add(stringRequest);
}
private void parseJSONresponse(String s)
{
try
{
JSONArray json = new JSONArray(s);
for (int i = 0; i < json.length(); i++)
{
JSONObject e = json.getJSONObject(i);
musers.add(new mobstat(e.getString("name"), e.getString("status"),e.getLong("time")));
SugarRecord.updateInTx(musers);
}
} catch (JSONException e)
{
e.printStackTrace();
}
}
}
I have tried Timer & Handler, these are working fine but the it makes app slow and not responding. Thread is not working. Please suggest some better way to run this method in background without any disturb to main thread.
create separate process for your service in manifest file might this help you
<manifest>
....
<application>
.....
<service android:name=".serv" android:process=":myprocess" >
</application>
</manifest>
Have you tried IntentService? It's an easy way of running time-consuming background task.
Modify your current implementation with IntentServices.
By default IntentServices runs in background thread. If using Services it uses main thread by default. Then you need to run a Thread inside service to make that execution block in background.
Go through this and this link for more information

Categories

Resources