FirebaseMessagingService is not getting called in AsyncTask's doInBackground - java

I have push Notification and I want to update realm objects when the phone gets a notification but when I try launch this:
RealmModelActiveUser actUser= realm.where(RealmModelActiveUser.class).equalTo("id",1).findFirst();
int myid= actUser.getUser().getUser_id();
new ServerBackgroundDownloadConversations(getApplicationContext()) {
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (!result.equals("Error")) {
Log.i("Conversation", "UPDATED");
}
}
}.execute(myid);
The program jumps into the constructor ServerBackgroundDownloadConversations(getApplicationContext()) but doesn't call doInBackground and I don't know why.
My AsyncTask:
public class ServerBackgroundCreateConversation extends AsyncTask<RealmModelConversations,Void,String> {
Context context;
Handler handler;
String out= "";
#SuppressLint("HandlerLeak")
public ServerBackgroundCreateConversation(Context context) {
this.context = context;
handler = new Handler() {
#Override
public void handleMessage(Message msg) {
Bundle bundle= msg.getData();
if (bundle!=null){
out = (String) bundle.get("response");
} else {
out= "Error";
}
}
};
}
#Override
protected String doInBackground(RealmModelConversations... params) {
RealmModelConversations newConv = params[0];
UploadImageApacheHttp uploadTask = new UploadImageApacheHttp();
uploadTask.doFileUpload(newConv.getWork(newConv.getIntWork()), newConv, handler);
while (out.equals("")){
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return out;
}
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(String result) {
if (!result.equals("]") || !result.equals("")){
/// prihlási nového user aj do active (login/register)
CreateNewConversation(result);
} else {
result="Error";
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
private void CreateNewConversation(String result){
Realm realm= Realm.getDefaultInstance();
try {
Gson gson = new Gson();
Type typeConv = new TypeToken<JsonSablonaConversations>() {
}.getType();
JSONObject pom;
JSONArray parentArray = new JSONArray(result);
JSONObject finalObject = parentArray.getJSONObject(0);
JsonSablonaConversations conversation = gson.fromJson(finalObject.toString(), typeConv);
final RealmModelConversations NewUserConv = new RealmModelConversations();
NewUserConv.setId_dialog(conversation.getId_dialog());
NewUserConv.setDate(conversation.getDate());
NewUserConv.setKey(conversation.getKey());
NewUserConv.setId_user(conversation.getId_user());
NewUserConv.setId_user2(conversation.getId_user2());
NewUserConv.setMeno(conversation.getMeno());
NewUserConv.setMeno2(conversation.getMeno2());
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
try {
realm.copyToRealmOrUpdate(NewUserConv);
} catch (Exception e) {
int pom=4;
}
RealmResults<RealmModelConversations> ru= realm.where(RealmModelConversations.class).findAll();
}
});
}
catch (Exception e) {
int ppp=4;
ppp++;
}finally {
realm.close();
}
}
}
I try calling this ↑ from an external thread which is called from a Service, but my AsyncTask has handler and handler needs to be in runOnUIthread and in Thread. I can't get Activity because the thread is called from a Service which doesn't have access to Activity.

I solved my problem with this code
public String postData(int myUserId) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.gallopshop.eu/OFY/getConversations.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id", Integer.toString(myUserId)));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String responseStr = EntityUtils.toString(response.getEntity());
return responseStr;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
return null;
}
I will try to put this method & after this method into simply thread, But maybe it's not needed because it's in a service.
Question - Do I put this into Thread or do you think it'll affect the performance of the app?

Related

Activity keeps restarting when I leave the activity and come back to it

I have two activities, When I will move from activity A to B, B keeps restarting or "refreshing", when i go back from B to A, it also keeps restarting. The code is very big, here I am posting area where I think problem causes :
Thread t = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
deviceStatus();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t.start();
this is deviceStatus();
public void deviceStatus(){
try {
RequestQueue requestQueue = Volley.newRequestQueue(InActivate.this);
String URL = "http://gickuwait-dev.com/electionapi/api/DeviceStatus";
JSONObject jsonBody = new JSONObject();
jsonBody.put("device_PK", device_ID2);
final String requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(response.equals("true")){
Intent intent = new Intent(InActivate.this, Vote.class);
startActivity(intent);
finish();
}else if(response.equals("false")) {
}
// Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString;
String json = null;
try {
json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
responseString = String.valueOf(json).trim();
ArrayList<DeviceStatusResponse> list = new ArrayList<DeviceStatusResponse>();
Type listType = new TypeToken<List<DeviceStatusResponse>>() {}.getType();
list = new Gson().fromJson(responseString, listType);
device_Status = list.get(0).getIsActive().toString();
// Toast.makeText(getApplicationContext(), ""+device_Status+" null ", Toast.LENGTH_LONG).show();
return Response.success(device_Status, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
in Activity B, i have the same code to check the device status from the database, any help would be appreciated
You can use Handle to check the repeated task.
private Handler delayHandler = new Handler();
private Runnable runnable = new Runnable() {
#Override
public void run() {
deviceStatus();
driverDelayHandler.postDelayed(runnable, 1000);
}
};
Don't forgot to cancel on onStop method.
delayHandler.removeCallbacks(runnable);

How can I set doInbackground finish its task before continuing the mainActivity?

These are my MainActivity:
database_connector wp_terms = new database_connector("SELECT * FROM `dse120071750`.`wp_terms` ",progressDialog,this);
wp_terms.execute();
wp_terms.onPreExecute();
try {
for (int i=0; i<wp_terms.getJsonArray().length(); i++){
JSONObject obj = wp_terms.getJsonArray().getJSONObject(i);
this.wp_terms.put(obj.getString("term_id"), obj.getString("name"));
}
} catch (JSONException e) {
e.printStackTrace();
}
DatabaseConnector:
package hk.hoome.www.mobilehoome;
public class database_connector extends AsyncTask<Void,Void, Void> {
//String mode;
HttpResponse response;
String sql;
JSONArray jsonArray;
searchPage searchPage;
public database_connector(String sql, searchPage searchPage){
//this.mode = mode;
this.sql = sql;
this.searchPage = searchPage;
jsonArray = new JSONArray();
}
#Override
protected Void doInBackground(Void... params) {
connect();
publishProgress();
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
}
public void connect() {
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);
nameValuePair.add(new BasicNameValuePair("sql", sql));
//nameValuePair.add(new BasicNameValuePair("mode", mode));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.hoome.hk/hoomeMobileApps/connectDB.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair, "UTF-8"));
response = httpClient.execute(httpPost);
HttpEntity httpEntity = response.getEntity();
String entityResponse = EntityUtils.toString(httpEntity);
Log.e("Entity Response ", entityResponse.substring(2));
jsonArray = new JSONArray(entityResponse.substring(2));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
public JSONArray getJsonArray(){
return jsonArray;
}
}
When I ran this code, for (int i=0; i<wp_terms.getJsonArray().length(); i++){ this results in a nullPointerException.
I believe that this is because doInbackground hasn't finished its process but mainActivity keeps running. How can I set that doInbackground has to be done before continue running the mainActivity?
SOLUTION?
try {
while (wp_posts.getJsonArray().equals(null))
Thread.sleep(1000);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
is this a good solution?
Use a callback in your database connector class and pass the completion callback. For the simplicity I'm using Runnable interface. In general, try to have your own interface and also to pass the params between the background thread and the main thread over your custom interface.
package hk.hoome.www.mobilehoome;
public class database_connector extends AsyncTask<Void,Void, Void> {
//String mode;
HttpResponse response;
String sql;
JSONArray jsonArray;
searchPage searchPage;
private Runnable activityCallback;
public void setCallback(Runnable callback) {
this.activityCallback = callback;
}
public database_connector(String sql, searchPage searchPage){
//this.mode = mode;
this.sql = sql;
this.searchPage = searchPage;
jsonArray = new JSONArray();
}
#Override
protected Void doInBackground(Void... params) {
connect();
publishProgress();
return null;
}
protected void onPostExecute(Void result) {
if(activityCallback != null) {
activityCallback.run();
}
}
#Override
protected void onProgressUpdate(Void... values) {
}
public void connect() {
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);
nameValuePair.add(new BasicNameValuePair("sql", sql));
//nameValuePair.add(new BasicNameValuePair("mode", mode));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.hoome.hk/hoomeMobileApps/connectDB.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair, "UTF-8"));
response = httpClient.execute(httpPost);
HttpEntity httpEntity = response.getEntity();
String entityResponse = EntityUtils.toString(httpEntity);
Log.e("Entity Response ", entityResponse.substring(2));
jsonArray = new JSONArray(entityResponse.substring(2));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
public JSONArray getJsonArray(){
return jsonArray;
}
}
In your MainActivity
database_connector wp_terms = new database_connector("SELECT * FROM `dse120071750`.`wp_terms` ",progressDialog,this);
wp_terms.setCallback(new Runnable() {
public void run() {
try {
for (int i=0; i<wp_terms.getJsonArray().length(); i++){
JSONObject obj = wp_terms.getJsonArray().getJSONObject(i);
this.wp_terms.put(obj.getString("term_id"), obj.getString("name"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
wp_terms.execute();
I also faced the same problem in one of my project, this is what might help you
public class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(String...params) {
String result;
//background tasks here.
return result;
}
protected void onPostExecute(String result) {
//task after doInBackground here.
}
}
doInBackground():
Override this method to perform a computation on a background thread.
onPostExecute():
Runs on the UI thread after doInBackground(Params...). The specified result is the value returned by doInBackground(Params...).
This method won't be invoked if the task was cancelled.
Parameters
result The result of the operation computed by doInBackground(Params...)
perform the background task in doInBackground method and the task after the background task(displaying toast or dialog) in onPostExecute(String result) method.
The result returned from doInBackground(String...params)method will be received as parameter in onPostExecute(String result) method in result parameter.
To use this code segment, from your main activity call new DownloadFilesTask().excute(param1,param2,...,paramn).
This parameters will be received in doInBackground(String...params) in params.
Write in comment if you face any problem.
Happy coding!!!

Android java parsing Json from url to object list

I would like to connect to a Api url, retrieve the json and store everything in a object list. Here is an example of what the url can return as Json.
The following code was given to me but it returns a error Cannot resolve method setOnResponse in my activity line 31
This is my activity.java
public class resultOverview_activity extends Activity implements onResponse{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_overview);
Bundle search_activity_data = getIntent().getExtras();
if(search_activity_data == null){
return;
}
String URL = "http://www.gw2spidy.com/api/v0.9/json/item-search/Sunrise";
AsyncTask parkingInfoFetch = new AsyncFetch(this);
parkingInfoFetch.setOnResponse(this);
parkingInfoFetch.execute(URL);
//Log.i("gw2Log", parkingInfoFetch.);
}
#Override
public void onResponse(JSONObject object) {
Log.d("Json Response", "Json Response" + object);
ResultClass resultClass = new ResultClass();
try {
resultClass.setCount(object.getInt("count"));
resultClass.setPage(object.getInt("page"));
resultClass.setLast_page(object.getInt("last_page"));
resultClass.setTotal(object.getInt("total"));
JSONArray array = new JSONArray(object.getString("results"));
for (int i = 0; i < resultClass.getTotal(); i++) {
JSONObject resultsObject = array.getJSONObject(i);
resultClass.setData_id(resultsObject.getInt("data_id"));
resultClass.setName(resultsObject.getString("name"));
resultClass.setRarity(resultsObject.getInt("rarity"));
resultClass.setRestriction_level(resultsObject
.getInt("restriction_level"));
resultClass.setImg(resultsObject.getString("img"));
resultClass.setType_id(resultsObject.getInt("type_id"));
resultClass.setSub_type_id(resultsObject.getInt("sub_type_id"));
resultClass.setPrice_last_changed(resultsObject
.getString("price_last_changed"));
resultClass.setMax_offer_unit_price(resultsObject
.getInt("max_offer_unit_price"));
resultClass.setMin_sale_unit_price(resultsObject
.getInt("min_sale_unit_price"));
resultClass.setOffer_availability(resultsObject
.getInt("offer_availability"));
resultClass.setSale_availability(resultsObject
.getInt("sale_availability"));
resultClass.setSale_price_change_last_hour(resultsObject
.getInt("sale_price_change_last_hour"));
resultClass.setOffer_price_change_last_hour(resultsObject
.getInt("offer_price_change_last_hour"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
AsyncFetch.java class
public class AsyncFetch extends AsyncTask<String, Void, JSONObject> {
public AsyncFetch(Context context) {
this.context = context;
}
private Context context;
private JSONObject jsonObject;
private onResponse onResponse;
public onResponse getOnResponse() {
return onResponse;
}
public void setOnResponse(onResponse onResponse) {
this.onResponse = onResponse;
}
#Override
protected JSONObject doInBackground(String... params) {
// TODO Auto-generated method stub
try {
HttpGet get = new HttpGet(params[0]);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
jsonObject = new JSONObject(result);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonObject;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
this.onResponse.onResponse(result);
}
public interface onResponse {
public void onResponse(JSONObject object);
}
}
And ofcourse the constructur ResultClass which i assume is not necessary to include here as code.
What does this error Cannot resolve method setOnResponse mean and how do i fix this?
Change this line:
AsyncTask parkingInfoFetch = new AsyncFetch(this);
To this:
AsyncFetch parkingInfoFetch = new AsyncFetch(this);
The error means that the line:
parkingInfoFetch.setOnResponse(this);
Is trying to call a method defined in the subclass AsyncFetch, but you have the variable defined as the parent class AsyncTask which has no method setOnResponse.

Get value from Async task in Activity

I have a class as shown below. It is in a .java file called NQRequestHandler.java and I want to call this from an Activity.java. But I'm having problems with the AsyncTask method. When I run it in the Activity.java file it returns a null
value when I try to log the value of Globals.PUBLIC_KEY from the Activity.
Log.v("RESULT", "Public KEY JSON from OnStart" + Globals.PUBLIC_KEY);
public class NQRequestHandler {
private static NQRequestHandler instance;
public static final String TAG = NQRequestHandler.class.getSimpleName();
private Context mContext;
public NQRequestHandler(Context context) {
mContext = context;
}
public static synchronized NQRequestHandler getInstance(Context context) {
if (instance == null)
instance = new NQRequestHandler(context);
return instance;
}
public class requestHandler extends AsyncTask<String, Void, JSONArray> {
RequestListener requestListener;
public JSONArray requestResult;
public requestHandler() {
}
public void setRequestListener(RequestListener requestListener) {
this.requestListener = requestListener;
}
#Override
protected JSONArray doInBackground(String... params) {
try {
String url = "http://www.someurl.com";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
List<NameValuePair> urlParameters = requestHandlerHelper(params);
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(urlParameters);
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded; charset=UTF-8"));
post.setEntity(entity);
HttpResponse response = client.execute(post);
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
Reader reader = new InputStreamReader(response.getEntity().getContent());
int contentLength = (int) response.getEntity().getContentLength();
Log.v(TAG, "Content Length DATA" + contentLength);
char[] charArray = new char[contentLength];
reader.read(charArray);
String responseData = new String(charArray);
JSONArray jsonResponse = new JSONArray(responseData);
return jsonResponse;
} catch (ClientProtocolException e) {
Log.i(TAG, "ClientProtocolException: ", e);
} catch (UnsupportedEncodingException e) {
Log.i(TAG, "UnsupportedEncodingException: ", e);
} catch (IOException e) {
Log.i(TAG, "IOException: ", e);
} catch (JSONException e) {
Log.i(TAG, "JSONException: ", e);
}
return null;
}
#Override
protected void onPostExecute(JSONArray results) {
if (results != null) {
requestListener.onRequestSuccess(results);
} else {
requestListener.onRequestFailed();
}
}
}
public interface RequestListener {
JSONArray onRequestSuccess(JSONArray data);
void onRequestFailed();
}
public void NQRequest(String... params) {
if (isNetworkAvailable()) {
requestHandler handler = new requestHandler();
RequestListener listener = new RequestListener() {
#SuppressWarnings("unchecked")
#Override
public JSONArray onRequestSuccess(JSONArray data) {
//TODO: Switch set data here
Log.v(TAG, "JSON FROM NQRequest" + data);
Globals.PUBLIC_KEY = String.valueOf(data);
return data;
}
#Override
public void onRequestFailed() {
Toast.makeText(mContext, "Network is unavailable. Request failed", Toast.LENGTH_LONG).show();
}
};
handler.setRequestListener(listener);
handler.execute(params);
} else {
Toast.makeText(mContext, "Network is unavailable", Toast.LENGTH_LONG).show();
}
}
private static List<NameValuePair> requestHandlerHelper(String... params) {
//Declare URL Parameter values
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
String[] requestActionArray = Globals.REQUEST_ACTION_ID;
int actionSwitch = -1;
String[] requestActionHeaders = null;
//Find URL Parameter Action Switch
for (int i = 0; i < requestActionArray.length; i++) {
if (requestActionArray[i].equalsIgnoreCase(params[params.length - 1])) {
actionSwitch = i;
}
}
//Set Action Switch ID Parameters
requestActionHeaders = NQActionHeader(actionSwitch);
//Set URL Parameters
for (int i = 0; i < requestActionHeaders.length; i++) {
urlParameters.add(new BasicNameValuePair(requestActionHeaders[i], params[i]));
}
return urlParameters;
}
private boolean isNetworkAvailable() {
ConnectivityManager manager =
(ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected() ? true : false;
}
private static String[] NQActionHeader(int actionSwitch) {
/* some code goes here */
}
}
In the Activity class looks like this:
public class Application extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
String message = "Hello World from Android";
Context mContext = getBaseContext();
NQRequestHandler.requestHandler handler = new NQRequestHandler.requestHandler();
NQRequestHandler requestHandler = NQRequestHandler.getInstance(mContext);
requestHandler.NQRequest(message, "sendPublicKey");
Log.v("RESULT", "Public KEY JSON from OnStart" + Globals.PUBLIC_KEY);
//Start Activity
Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The call to NQRequest in the Activity initiates the call to AsyncTask in the Activity. Any help with this? How do I implement a callback in the Activity.java to get method from OnRequestSuccess(); in the NQRequest()? Note: I'm trying to call the method in Activity.java in other multiple Activity.java files
i modified the structure for your reference.
Modified of requestHandler :-
//**** e.g.
class requestHandler extends AsyncTask<Object, Void, JSONArray> {
// define a caller
String requester;
Application caller;
YourEachActivityClass1 caller1;
//create a Constructor for caller;
public requestHandler (Application caller) {
// TODO Auto-generated constructor stub
this.caller = caller;
}
public requestHandler (YourEachActivityClass1 caller1) {
// TODO Auto-generated constructor stub
this.caller1 = caller1;
}
///&& method doInBackground
#Override
protected JSONArray doInBackground(Object... params) {
.....
//your process is here
//custom your returning jsonarray
try {
Context context = (Context) params[0];
Log.i(TAG, "context :"+context.getClass().getSimpleName());
requester = (Integer) params[1];
String message = (String) params[2];
String public= (String) params[3]
String url = "http://www.someurl.com";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
List<NameValuePair> urlParameters = requestHandlerHelper(params);
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(urlParameters);
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded; charset=UTF-8"));
post.setEntity(entity);
HttpResponse response = client.execute(post);
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
Reader reader = new InputStreamReader(response.getEntity().getContent());
int contentLength = (int) response.getEntity().getContentLength();
Log.v(TAG, "Content Length DATA" + contentLength);
char[] charArray = new char[contentLength];
reader.read(charArray);
String responseData = new String(charArray);
JSONArray jsonResponse = new JSONArray(responseData);
Globals.PUBLIC_KEY = String.valueOf(jsonResponse);
return jsonResponse;
} catch (ClientProtocolException e) {
Log.i(TAG, "ClientProtocolException: ", e);
} catch (UnsupportedEncodingException e) {
Log.i(TAG, "UnsupportedEncodingException: ", e);
} catch (IOException e) {
Log.i(TAG, "IOException: ", e);
} catch (JSONException e) {
Log.i(TAG, "JSONException: ", e);
}
return null;
}
////&& return JSONArray back to ur activity class here by pass in caller
protected void onPostExecute(JSONArray jsonarray) {
if(requester.equals("IM_Application"))
caller.onBackgroundTaskCompleted(jsonarray);
else if(requester.equals("IM_ACTIVITY_1"))
caller1.onBackgroundTaskCompleted(jsonarray);
}
}
Application.class get ur json object:-
public class Application extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
String message = "Hello World from Android";
new requestHandler(this).execute(getActivity(), "IM_Application", message, "sendPublicKey");
} catch (Exception e) {
e.printStackTrace();
}
}
//your returning result
public void onBackgroundTaskCompleted(JSONArray jsonarray) {
Log.i("TAG", jsonarray:"+jsonarray);
if(jsonarray!=null){
//process your jsonarray to get the Globals.PUBLIC_KEY)here
Log.v("onBackgroundTaskCompleted", "Public KEY JSON from OnStart" + Globals.PUBLIC_KEY);
//Start Activity
Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}else{
Toast.makeText(mContext, "Network is unavailable. Request failed", Toast.LENGTH_LONG).show();
}
}
}
Gd Luck :)
The log from OnStart should return a null value for Globals.PUBLIC_KEY. You have just set an asynchronous task to run to set that value. It has not run yet by the time that log statement executes. You should receive the log input from the
Log.v(TAG, "JSON FROM NQRequest" + data);
call. That will mostly happen after your activity has finished onCreate, as it is an asynchronous call.
Fixed it works now.
public class HQHandler extends AsyncTask<String, Void, JSONArray> {
public static final String TAG = HQHandler.class.getSimpleName();
private static HQHandler instance;
RequestListener requestListener;
JSONArray requestResult;
Context mContext;
public HQHandler(Context context) {
this.mContext = context;
}
public static synchronized HQHandler getInstance(Context context) {
if (instance == null)
instance = new HQHandler(context);
return instance;
}
public void setRequestListener(RequestListener requestListener) {
this.requestListener = requestListener;
}
public JSONArray getRequestResult() {
return this.requestResult;
}
#Override
protected JSONArray doInBackground(String... params) {
try {
String url = "http://www.someurl.com";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
List<NameValuePair> urlParameters = requestHandlerHelper(params);
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(urlParameters);
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded; charset=UTF-8"));
post.setEntity(entity);
HttpResponse response = client.execute(post);
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
Reader reader = new InputStreamReader(response.getEntity().getContent());
int contentLength = (int) response.getEntity().getContentLength();
Log.v(TAG, "Content Length DATA" + contentLength);
char[] charArray = new char[contentLength];
reader.read(charArray);
String responseData = new String(charArray);
JSONArray jsonResponse = new JSONArray(responseData);
return jsonResponse;
} catch (ClientProtocolException e) {
Log.i(TAG, "ClientProtocolException: ", e);
} catch (UnsupportedEncodingException e) {
Log.i(TAG, "UnsupportedEncodingException: ", e);
} catch (IOException e) {
Log.i(TAG, "IOException: ", e);
} catch (JSONException e) {
Log.i(TAG, "JSONException: ", e);
}
return null;
}
#Override
protected void onPostExecute(JSONArray results) {
if (results != null) {
requestListener.onRequestSuccess(results);
} else {
requestListener.onRequestFailed();
}
}
public interface RequestListener {
JSONArray onRequestSuccess(JSONArray data);
void onRequestFailed();
}
public JSONArray HQRequest(String... params) throws ExecutionException, InterruptedException, JSONException {
JSONArray result;
if (!isNetworkAvailable()) {
Toast.makeText(mContext, "Network is unavailable", Toast.LENGTH_LONG).show();
return null;
}
HQHandler handler = new HQHandler(this.mContext);
RequestListener listen = new RequestListener() {
#SuppressWarnings("unchecked")
#Override
public JSONArray onRequestSuccess(JSONArray data) {
return data;
}
#Override
public void onRequestFailed() {
Toast.makeText(mContext, "Network is unavailable. Request failed", Toast.LENGTH_LONG).show();
}
};
handler.setRequestListener(listen);
result = this.requestResult = handler.execute(params).get();
return result;
}
}

Android login not working

Hi Please Can someone help me look at this code? Don't know what am doing wrong,But the try block doesn't run. instead it goes to the catch block.
public void onClick(View arg0) {
//Toast.makeText(getBaseContext(), "connecting",Toast.LENGTH_SHORT).show();
// TODO Auto-generated method stub
httpclient = new DefaultHttpClient();
htpost = new HttpPost("http://10.0.2.2/fanaticmobile/log_in.php");
uname= username.getText().toString();
pass= password.getText().toString();
try {
namearray = new ArrayList<NameValuePair>();
namearray.add(new BasicNameValuePair("username", uname));
namearray.add(new BasicNameValuePair("password", pass));
htpost.setEntity(new UrlEncodedFormEntity(namearray));
response= httpclient.execute(htpost);
if(response.getStatusLine().getStatusCode()==200){
entity= response.getEntity();
if(entity != null){
InputStream stream = entity.getContent();
JSONObject jresponse = new JSONObject(ConvertInput(stream));
String logged= jresponse.getString("logged");
login_err.setText(""+logged);
if(logged.equals("true")){
Toast.makeText(getBaseContext(), "Successfull",Toast.LENGTH_SHORT).show();
//String retname= jresponse.getString("name");
//String retmail= jresponse.getString("email");
}else if(logged.equals("false")){
String message=jresponse.getString("message");
Toast.makeText(getBaseContext(), message,Toast.LENGTH_SHORT).show();
}
}
}else{
}
}
catch (Exception e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), "Poor Connection",Toast.LENGTH_SHORT).show();
}
}//
This is the function to read the json object
private static String ConvertInput(InputStream is){
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line ="";
try {
while((line = reader.readLine())!= null){
sb.append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
is.close();
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
}
return sb.toString();
}// end of convert function
Please am new to this and i followed a tutorial to this point,but mine is not working. Have set permission(internet) in the manifest file
I have a suggestion Try to Use AsyncHttpclient for getting responses from server no need of this long codes.
http://loopj.com/android-async-http/
AsyncHttpClient asyncHttpClient=new AsyncHttpClient();
RequestParams params=new RequestParams();
params.put("username", uname);
params.put("password", pass);
asyncHttpClient.post("http://10.0.2.2/fanaticmobile/log_in.php", params,new AsyncHttpResponseHandler(){
#Override
public void onFailure(Throwable arg0, String arg1) {
// TODO Auto-generated method stub
super.onFailure(arg0, arg1);
}
#Override
public void onSuccess(String arg0) {
// TODO Auto-generated method stub
super.onSuccess(arg0);
}
});
Just include the jar file in your project it will be simple to use.
Like already been stated in the comments, you're running a network operation in your main thread (the UI thread). This is not only discouraged (lengthy operations should never use the Main Thread), but also forbidden in the case of networking.
response= httpclient.execute(htpost)
^ this fails.
Read how to move that code to an AsyncTask and do it the right way in the official google reference. Googling AsyncTask will help too.
A Pseudo Code version would be:
public class YourTask extends AsyncTask<Void, Void, Void>{
YourListener mListener;
public YourTask(final YourListener listener) {
mListener = listener;
}
#Override
protected Void doInBackground(final Void... params) {
// do your lengthy operation here
return null;
}
#Override
protected void onPostExecute(Void result) {
mListener.onVeryLongTaskDone();
}
public interface YourListener {
public void onVeryLongTaskDone();
}
}
Then make your activity implement that "YourListener" interface and the method onVeryLongTaskDone() will be called.
How do you start the task?
in your onClick method:
(new YourTask(YourActivityName.this)).execute();

Categories