calling multiple methods in oncreate method in android - java

I have multiple methods to be called when activity is started. I have added those methods in the oncreate method. The problem is when the activity is started some methods are called some or not called. How do i call all the methods when the activity is started.
My code is
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
client.post("http://localhost/website/getdbrowcount.php",params ,new AsyncHttpResponseHandler()
{
public void onSuccess(String response)
{
try
{
Log.d("home", "success");
JSONObject obj = new JSONObject(response);
Log.d("home", obj.toString());
System.out.println(obj.get("count"));
syncDB();
sync();
subsync();
syncfeature();
syncelec();
syncconnector();
synccontrols();
synckeypad();
syncmech();
syncorder();
syncpower();
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void onFailure(int statusCode, Throwable error,String content)
{
if(statusCode == 404)
{
update.setText("The update has been cancelled. Please update via Settings to work"
+ " with latest Sonetonix product data");
Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
btn1.setEnabled(true);
btn1.setTextColor(Color.parseColor("#FFFFFF"));
}
else if(statusCode == 500)
{
update.setText("The update has been cancelled. Please update via Settings to work"
+ " with latest Sonetonix product data");
Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
btn1.setEnabled(true);
btn1.setTextColor(Color.parseColor("#FFFFFF"));
}
else
{
update.setText("The update has been cancelled. Please update via Settings to work"
+ " with latest Sonetonix product data");
Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet]", Toast.LENGTH_LONG).show();
btn1.setEnabled(true);
btn1.setTextColor(Color.parseColor("#FFFFFF"));
}
Log.d("home", "failure");
}
});
}
In the code when OnSuccess the methods has to be called but only syncDB(),sync() is called and rest are not called . What change should i make in the code to resolve this issue.
Please help

It is because in the sync() method or possibly at the start of the subsync() method your program is throwing an error. Because of the try/catch block, you are allowing the program to continue.
Check the method for an error and fix that.

Related

Checking for in-app purchases

Following instructions from: https://developer.android.com/training/in-app-billing/purchase-iab-products.html under Query Purchased Items, I am checking for purchased items.
My code looks like this:
private void lookForPurchases() {
IabHelper.QueryInventoryFinishedListener lookForPurchasesListener = new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
if (result.isFailure()) {
Log.e(TAG, "Error checking for purchases:" + result.toString());
}
else {
Log.d(TAG, "Processing purchases." + inventory.toString());
if(inventory.hasPurchase(SKU_LEXCOINS_100)){
Purchase purchase = inventory.getPurchase(SKU_LEXCOINS_100);
consumeCoinPurchase(purchase);
}
if(inventory.hasPurchase(SKU_LEXCOINS_550)){
Purchase purchase = inventory.getPurchase(SKU_LEXCOINS_550);
consumeCoinPurchase(purchase);
}
if(inventory.hasPurchase(SKU_LEXCOINS_1200)){
Purchase purchase = inventory.getPurchase(SKU_LEXCOINS_1200);
consumeCoinPurchase(purchase);
}
}
}
};
Log.i(TAG, "Looking for purchases");
if(inAppBillingHelper == null) {
Log.e(TAG, "Null preventing query inventory");
} else {
try {
inAppBillingHelper.queryInventoryAsync(lookForPurchasesListener);
} catch (IabHelper.IabAsyncInProgressException ex) {
Log.e(TAG, "Error retrieving purchases.", ex);
}
}
}
In the log, though, the last thing I get is "Looking for purchases" with nothing following. It looks like I should get something on any branch, so, does anyone see what I'm doing wrong?
No errors or anything, it just never seems to come back.
The problem was on the line handler.post deep in IabHelper (Google Code) where it was executing my callback I was passing in. The handler.post was getting called, buy my callback never was. I'm not sure how that happened.
I replaced the handler.post with a AsyncTask and posted the call of my callback in the onPostExecute method to get it run on the UI thread. This appears to have solved my problem.

How to get object out of inner class

I am trying to make this application in Android, I am getting data from foursquare's API in JSON format and I need to Parse it to present it in another intent.
I am using Android's volley library to get the JSON but the problem is the onResponse() function of JsonObjectRequest has no return parameter.so I cannot get the JSON object gotten from url outside of the the onResponse.
I haven't worked with volley before and hence don't know much about it, any help is appreciated. Here is the code that I am trying to make it work.
Edit: The main problem I'm facing is that I cannot assign a value to global variable in this case myPlaces inside the JsonObjectRequest's onResponse method. Or to be exact, the variable assigned inside means nothing outside, thus in the last line
Toast.makeText(MainActivity.this, myPlaces[2].getName(), Toast.LENGTH_LONG).show();
when I try to access the myPlaces[2] it gives me an null pointer exception.
Thanks.
public void onClick(View v) {
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(urlString, null, new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject meta = response.getJSONObject("meta");
String status = meta.getString("code");
Toast.makeText(MainActivity.this, status, Toast.LENGTH_SHORT).show();
if(status.equals("200"))
{
JSONObject responseJson = response.getJSONObject("response");
JSONArray venues = responseJson.getJSONArray("venues");
Places[] tempPlaces = new Places[venues.length()];
for (int i = 0 ; i < venues.length(); i++)
{
Places place = new Places();
JSONObject venueObject = venues.getJSONObject(i);
place.setName(venueObject.getString("name"));
JSONObject locatVenue = venueObject.getJSONObject("location");
place.setLat(locatVenue.getDouble("lat"));
place.setLon(locatVenue.getDouble("lng"));
tempPlaces[i] = place;
}
Toast.makeText(MainActivity.this, tempPlaces[2].getName(), Toast.LENGTH_LONG).show();
myPlaces = tempPlaces;
}
else
{
Toast.makeText(MainActivity.this, "No response from API", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "There is some error here", Toast.LENGTH_LONG).show();
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "There has been some error", Toast.LENGTH_LONG).show();
}
});
requestQueue.add(jsonObjectRequest);
Toast.makeText(MainActivity.this, myPlaces[2].getName(), Toast.LENGTH_LONG).show();
Volley itself isn't an inner class; the response is an anonymous class.
You don't need a return in Volley, you just use the variables already defined in your class.
I'm assuming myPlaces is a field in your class? Otherwise, I'm not sure where it is declared outside the onClick..
This line assigns myPlaces and looks like it would work fine
myPlaces = tempPlaces;
You could define a method in your class to parse the whole JSONObject instead of needing to return from Volley. This just passes the logic to another method, so you don't need to think about "returning" inside Volley.
public void parseJSON(JsonObject object)
And pass the response from volley into that and do your normal parsing and variable assignment and you can Toast myPlaces inside that method.
Also, note that Volley is asynchronous, meaning you aren't guaranteed an immediate result, so
Toast.makeText(MainActivity.this, myPlaces[2].getName(), Toast.LENGTH_LONG).show();
Would likely have thrown either a NullPointerException or IndexOutOfBoundsException because myPlaces was either undeclared or empty before the Volley request. I say that because it does not appear to be assigned before the Volley request.

Toast cause NPE on Samsung Galaxy S5 with Android 5 [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
Here's code of Splash Screen (it's not my desire, but client) - the only thing I've done - just to replace sone code with loading data to this activity:
public class SplashActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.API_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
GetAll getAllProducts = retrofit.create(GetAll.class);
Call<ArrayList<Products>> call = getAllProducts.getAll(Constants.PARTNER_ID,
WaterFragment.getMD5Hash(Constants.PARTNER_ID + Constants.API_KEY));
call.enqueue(new Callback<ArrayList<Products>>() {
#Override
public void onResponse(Response<ArrayList<Products>> response, Retrofit retrofit) {
if (response.body() != null) {
ActiveAndroid.beginTransaction();
try {
ProductsDMC product;
for (Products p : response.body()) {
if (new Select().from(ProductsDMC.class).where("product_id = ?", p.id).executeSingle() != null) {
product = new Select().from(ProductsDMC.class).where("product_id = ?", p.id).executeSingle();
product.price = p.price;
} else {
product = new ProductsDMC(p.id, p.article, p.title, p.price, p.amount, p.category_id,
p.brand_id, p.description, p.photo[0], p.option != null ? p.option.bottle_price : "0");
}
product.save();
}
ActiveAndroid.setTransactionSuccessful();
} finally {
ActiveAndroid.endTransaction();
}
}else{
Toast.makeText(SplashActivity.this, "Try later!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure (Throwable t){
Toast.makeText(SplashActivity.this, "Check your connection!", Toast.LENGTH_SHORT).show();
Log.d("LoloPolo", t.getMessage().toString());
}
});
Intent intent = new Intent(this, ListOrdersActivity.class);
startActivity(intent);
finish();
}
}
Tonight my crashlytic send info about crash on app:
Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
at ru.luny.aqualuxe.activity.SplashActivity$3.onFailure(SplashActivity.java:142)
at retrofit.ExecutorCallAdapterFactory$ExecutorCallback$2.run(ExecutorCallAdapterFactory.java:94)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5832)
at java.lang.reflect.Method.invoke(Method.java)
It's about this:
Toast.makeText(SplashActivity.this, "Try later!", Toast.LENGTH_SHORT).show();
I really don't understand - how Toast.makeText().show can cause NPE))
Could you help me please?
EDIT
It seems strange but crashlytics shows me wrong place of error code string.
It's not about toast but debug-loggin with getting message from exception.
Problem is t.getMessage().toString()
You are getting NPE in onFailure (Throwable t) section . For testing case add ""+
#Override
public void onFailure (Throwable t){
Toast.makeText(SplashActivity.this, "Check your connection!", Toast.LENGTH_SHORT).show();
Log.d("LoloPolo",""+ t.getMessage().toString());
}
it's highly problem that the NPE is due of Log.d("LoloPolo", t.getMessage().toString());. Not always getMessage() returns a valid object. Printing t should be enough. E.g.
Log.d("LoloPolo", "Error", t);
(have a look here)
also those callback don't run on the UI Thread. I wont use them to show a `Toast.

Volley request too slow

My app crashes because the images ArrayList is empty when I set the adapter, I figured that out by putting a toast message right after I parse my JSON request, and a Toast message after I initialize my adapter, "second" gets printed first on screen and the app crashes right after, does it have to do with my internet? Or am I missing something, here's my code, thanks!
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page);
mViewPager = (ViewPager) findViewById(R.id.view_pager);
mVolleySingleton = VolleySingleton.getInstance();
mRequestQueue = mVolleySingleton.getRequestQueue();
//First Toast message inside this method
sendAPIRequest();
//after you get the images
mCustomSwipeAdapter = new CustomSwipeAdapter(this, images);
//SECOND TOAST
Toast.makeText(getApplicationContext(), "Second", Toast.LENGTH_LONG).show();
mViewPager.setAdapter(mCustomSwipeAdapter);
mCustomSwipeAdapter.notifyDataSetChanged();
}
public void sendAPIRequest(){
String requestURL = "";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, requestURL, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
parseJSONResponse(response);
//FIRST TOAST : SHOULD BE CALLED FIRST
Toast.makeText(getApplicationContext(), "First", Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
mRequestQueue.add(jsonObjectRequest);
}
public void parseJSONResponse(JSONObject response) {
if (response != null || response.length() != 0) {
try {
JSONObject GObject = response.getJSONObject("game");
String name = "N/A";
if (GObject.has("name") && !GObject.isNull("name")) { name = GObject.getString("name"); }
if (GObject.has("screenshots") && !GObject.isNull("screenshots")) {
JSONArray screenShotsArray = GObject.getJSONArray("screenshots");
for (int i = 0; i < screenShotsArray.length(); i++){
JSONObject screenshot = screenShotsArray.getJSONObject(i);
String screenshotURL = screenshot.getString("url");
images.add(screenshotURL);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Does it have to do with my internet? Or am I missing something ...
Both. It happens because you have a race condition.
From what I can make out, your images list is being populated asynchronously by the onResponse callback. Basically, that happens when your app gets the responses to the API requests that it is making. That is going to take at least milliseconds, and possibly seconds (or longer).
But your app is (so you say) crashing soon after the swipe adapter is registered, and the evidence is that the images list has not been populated.
There are three possibilities:
There is something wrong with the requests you are sending which is causing the API requests to not give you any response. (Hypothetically, you could have authentication wrong or something.)
The API requests are taking a long time because of internet connection speed, congestion, or the remote server being slow.
The API requests are taking a short time ... but the adapter registration is even quicker.
If (hypothetically) there is a problem with your requests you will need to fix that. But both of the other scenarios have to be fixed by:
modifying the code that uses the images to work properly if there are no images (yet), or
modifying the code to wait until the image loading has completed before registering the adapter.
Please use this code in your onResponse callback :
//after you get the images
mCustomSwipeAdapter = new CustomSwipeAdapter(this, images);
//SECOND TOAST
Toast.makeText(getApplicationContext(), "Second", Toast.LENGTH_LONG).show();
mViewPager.setAdapter(mCustomSwipeAdapter);
mCustomSwipeAdapter.notifyDataSetChanged();
Volley adds your requests in queue , so better do all the dependent tasks in Response or Error callback only.

automated email sending failure

I am using this article to help me send automated emails, but I am having an issue in which nothing seems to be happening and no errors are generated.
I used AsyncTask but it is not sending the mail at all.
public class Sender extends AsyncTask< Void, Void, Void> {
private Exception exception;
protected Void doInBackground(String... arg0) {
Log.v("aws", "OPEN asa");
Mail m = new Mail("email#email.com", "password");
String[] toArr = {"to#mail.com"};
m.setTo(toArr);
m.setFrom("from#gmail.com");
m.setSubject("This is an email sent using my Mail JavaMail wrapper from an >Android device.");
m.setBody("Email body.");
try {
//m.addAttachment("/sdcard/filelocation");
if(m.send()) {
Log.v("aws", "OK SENT");
} else {
Log.v("aws", "NOT SENT");
}
} catch(Exception e) {
Log.v("aws", "EXCEPTION . NOT SENT");
}
return null;
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
return null;
}
protected void onPostExecute(Void... arg0) {
// TODO: check this.exception
// TODO: do something with the feed
}
}
I have used new Sender().execute(); to execute the task, but nothing is happening and no errors are being thrown.
What am I doing wrong?
EDIT
Code has two doInBackground such that second overridden my working doInBackground
Be careful, you have two doInBackground() methods in your code, and the #Override version is what gets executed by the AsyncTask. Just move the code from the wrong doInBackground() version to the right one and delete the wrong one.

Categories

Resources