I am trying to integrate Stripe into my app. Once a user is created in my apps onboarding, they need to create an account with stripe to get payments. It keeps getting an error at
try {
accountLink = AccountLink.create(linkParams);
} catch (StripeException e) {
e.printStackTrace();
Log.e("LINK_PARAMS ERROR: ", e.toString());
}
The try{catch} is not catching the error so I am not seeing what exactly is going on. Can anyone shed some light on this for me? I just need to access the onboarding for Stripe, then redirect back to my app. I have read so many articles, I may have my wires crossed.
Android Manifest
<activity
android:name=".ui.stripeTools.ConnectWithStripeActivity"
android:label="#string/title_activity_connect_with_stripe"
android:theme="#style/Theme.Godsvong.NoActionBar"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSER"/>
<data
android:scheme="app"
android:host="godsvognapp.com"/>
</intent-filter>
</activity>
Activity Class:
public class ConnectWithStripeActivity extends AppCompatActivity {
private static final String RETURN_URL = "app://godsvognapp.com";
private OkHttpClient httpClient = new OkHttpClient();
private ActivityConnectWithStripeBinding binding;
private Account account = new Account();
private AccountLink accountLink = new AccountLink();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Stripe.apiKey = MainActivity.STRIPE_KEY;
Address address = new Address();
address.setLine1(MainActivity.mUser.getmAddress());
address.setCity(MainActivity.mUser.getmCity());
address.setState(MainActivity.mUser.getmState());
address.setPostalCode(MainActivity.mUser.getmZipCode());
Person individual = new Person();
individual.setAddress(address);
individual.setFirstName(MainActivity.mUser.getmFirstName());
individual.setLastName(MainActivity.mUser.getmLastName());
individual.setPhone(MainActivity.mUser.getmPhoneNumber());
individual.setEmail(MainActivity.mUser.getmEmailAddress());
account.setIndividual(individual);
AccountLinkCreateParams linkParams = AccountLinkCreateParams
.builder()
.setRefreshUrl(RETURN_URL)
.setReturnUrl(RETURN_URL)
.setType(AccountLinkCreateParams.Type.ACCOUNT_ONBOARDING)
.setCollect(AccountLinkCreateParams.Collect.EVENTUALLY_DUE)
.build();
try {
accountLink = AccountLink.create(linkParams);
} catch (StripeException e) {
e.printStackTrace();
Log.e("LINK_PARAMS ERROR: ", e.toString());
}
AccountCreateParams params = AccountCreateParams
.builder()
.setType(AccountCreateParams.Type.EXPRESS)
.build();
try {
account = Account.create(params);
} catch (StripeException e) {
e.printStackTrace();
Log.e("ACCOUNT ERROR: ", e.toString());
}
binding = ActivityConnectWithStripeBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
Button connectWithStripe = (Button) findViewById(R.id.connect_with_stripe);
connectWithStripe.setOnClickListener(view -> {
WeakReference<Activity> weakActivity = new WeakReference<>(this);
Request request = new Request.Builder()
.url(accountLink.getUrl())
.post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), ""))
.build();
httpClient.newCall(request)
.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
}
#Override
public void onResponse(#NotNull Response response) throws IOException {
final Activity activity = weakActivity.get();
if (activity == null) {
return;
}
if (response.isSuccessful()){
NavController navController = Navigation.findNavController(view);
navController.navigate(R.id.nav_home);
}
if (!response.isSuccessful() || response.body() == null) {
// Request failed
} else {
String body = response.body().string();
try {
JSONObject responseJson = new JSONObject(body);
String url = responseJson.getString(accountLink.getUrl());
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.launchUrl(view.getContext(), Uri.parse(url));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
});
}
}
Here is the Logcat:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.hsquaredtechnologies.godsvong, PID: 12735
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.hsquaredtechnologies.godsvong/com.hsquaredtechnologies.godsvong.ui.stripeTools.ConnectWithStripeActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:4037)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4203)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2440)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:226)
at android.os.Looper.loop(Looper.java:313)
at android.app.ActivityThread.main(ActivityThread.java:8641)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:567)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1133)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1668)
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:115)
at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:103)
at java.net.InetAddress.getAllByName(InetAddress.java:1152)
at com.android.okhttp.Dns$1.lookup(Dns.java:41)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:178)
at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:144)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:86)
at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:176)
at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:128)
at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:97)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:289)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:232)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:465)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:131)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:262)
at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getOutputStream(DelegatingHttpsURLConnection.java:219)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:30)
at com.stripe.net.HttpURLConnectionClient.createStripeConnection(HttpURLConnectionClient.java:124)
at com.stripe.net.HttpURLConnectionClient.requestStream(HttpURLConnectionClient.java:33)
at com.stripe.net.HttpURLConnectionClient.request(HttpURLConnectionClient.java:68)
at com.stripe.net.HttpClient$$ExternalSyntheticLambda2.apply(Unknown Source:2)
at com.stripe.net.HttpClient.sendWithTelemetry(HttpClient.java:66)
at com.stripe.net.HttpClient.requestWithTelemetry(HttpClient.java:83)
at com.stripe.net.HttpClient.lambda$requestWithRetries$0$com-stripe-net-HttpClient(HttpClient.java:145)
at com.stripe.net.HttpClient$$ExternalSyntheticLambda1.apply(Unknown Source:2)
at com.stripe.net.HttpClient.sendWithRetries(HttpClient.java:109)
at com.stripe.net.HttpClient.requestWithRetries(HttpClient.java:145)
at com.stripe.net.LiveStripeResponseGetter.request(LiveStripeResponseGetter.java:58)
at com.stripe.net.ApiResource.request(ApiResource.java:181)
at com.stripe.net.ApiResource.request(ApiResource.java:171)
at com.stripe.model.AccountLink.create(AccountLink.java:73)
at com.stripe.model.AccountLink.create(AccountLink.java:63)
E/AndroidRuntime: at com.hsquaredtechnologies.godsvong.ui.stripeTools.ConnectWithStripeActivity.onCreate(ConnectWithStripeActivity.java:90)
at android.app.Activity.performCreate(Activity.java:8282)
at android.app.Activity.performCreate(Activity.java:8262)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1329)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:4011)
... 12 more
I/Process: Sending signal. PID: 12735 SIG: 9
Related
I had built the app 3 days ago and the app was working fine.
yesterday I updated the Kotlin plugin to 1.3.71-studio3.6-1
after that when I build my app and run it on my phone then after login, the main activity does not launch and the app stops working but I am getting a successful login in my Firebase.
If I try to reopen the app, it does not open.
all other activities are working fine but main_activity does not.
the code of main activity was not modified
this is my manifest file
<application
android:allowBackup="false"
android:icon="#mipmap/g_c"
android:label="#string/app_name"
android:roundIcon="#mipmap/g_c_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".otp" />
<activity android:name=".Register" />
<activity android:name=".Login">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" />
</application>
</manifest>
logcat error
03-30 01:40:05.051 6724-6724/com.trackerbin.guardchecker E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.trackerbin.guardchecker, PID: 6724
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.trackerbin.guardchecker/com.trackerbin.guardchecker.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.ads.AdView.loadAd(com.google.android.gms.ads.AdRequest)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3319)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
at android.app.ActivityThread.access$1100(ActivityThread.java:229)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7325)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.ads.AdView.loadAd(com.google.android.gms.ads.AdRequest)' on a null object reference
at com.trackerbin.guardchecker.MainActivity.onCreate(MainActivity.java:63)
at android.app.Activity.performCreate(Activity.java:6904)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3266)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
at android.app.ActivityThread.access$1100(ActivityThread.java:229)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7325)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
MainActivity
public class MainActivity extends AppCompatActivity {
private Button mreport;
private Button mon;
private Button msignout;
private FirebaseAuth fAuth;
private Spinner mtower;
private ProgressBar mBar;
//AD
private AdView mAdView;
// Access a Cloud Firestore instance from your Activity
private final FirebaseFirestore db = FirebaseFirestore.getInstance();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mreport = findViewById(R.id.button);
mon = findViewById(R.id.onn);
fAuth = FirebaseAuth.getInstance();
mtower = findViewById(R.id.tower);
msignout = findViewById(R.id.signout);
mBar = findViewById(R.id.bar);
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
mAdView = findViewById(R.id.adViewR);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
if (fAuth.getCurrentUser() == null) {
startActivity(new Intent(getApplicationContext(), Login.class));
finish();
}
final String email = fAuth.getCurrentUser().getEmail();
final String phone = fAuth.getCurrentUser().getPhoneNumber();
mreport.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
mBar.setVisibility(View.VISIBLE);
String tower = mtower.getSelectedItem().toString();
String currentTime = new SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(new Date());
String currentDate = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date());
Map<String, Object> values = new HashMap<>(); values.put(currentTime,email + phone);
db.collection("tower").document(tower)
.collection(currentDate).document("duty")
.collection("off").document(currentTime).set(values);
mBar.setVisibility(View.INVISIBLE);
Toast.makeText(MainActivity.this, "THANK YOU FOR REPORTING !", Toast.LENGTH_SHORT).show();
}
});
mon.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
mBar.setVisibility(View.VISIBLE);
String tower = mtower.getSelectedItem().toString();
String currentTime = new SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(new Date());
String currentDate = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date());
Map<String, Object> values = new HashMap<>(); values.put(currentTime,email + phone);
db.collection("tower").document(tower)
.collection(currentDate).document("duty")
.collection("on").document(currentTime).set(values);
mBar.setVisibility(View.INVISIBLE);
Toast.makeText(MainActivity.this, "THANK YOU FOR REPORTING !", Toast.LENGTH_SHORT).show();
}
});
msignout.setOnClickListener
(
new View.OnClickListener()
{
#Override
public void onClick(View v) {
fAuth.signOut();
startActivity(new Intent(getApplicationContext(), Login.class));
finish();
}
}
);
}
#Override
public void onBackPressed() {
finishAffinity();
}
}
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" />
<!-- Sample AdMob App ID: ca-app-pub-3940256099942544~3347511713 -->
insert your own admob app id inside value="XXXXXXX"/>
Trying to migrate from Parse to OneSignal and I am stuck on how to start a new Activity after the user clicks on a push notification. My handler is working, the log shows the text, the issue seems to be how to gain access to the application context from within my push opened handler. The example code is vague, getApplicationContext() does not work without first doing something else.
One post I came upon, unrelated to OneSignal, suggests extending the Application class to gain access to the application context. This did not produce any syntax errors but my app crashes.
Code:
package com.linkedresponder.onesignal;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
import com.onesignal.OSNotificationAction;
import com.onesignal.OSNotificationOpenResult;
import com.onesignal.OneSignal;
import org.json.JSONObject;
class NotificationOpenHandler extends Application implements OneSignal.NotificationOpenedHandler {
// This fires when a notification is opened by tapping on it.
private Context mContext;
#Override
public void onCreate() {
this.mContext = getApplicationContext();
}
#Override
public void notificationOpened(OSNotificationOpenResult result) {
OSNotificationAction.ActionType actionType = result.action.type;
JSONObject data = result.notification.payload.additionalData;
String customKey;
if (data != null) {
customKey = data.optString("customkey", null);
if (customKey != null) {
Log.i("OneSignalExample", "customkey set with value: " + customKey);
} else {
Log.i("OneSignalExample", "No data");
}
}
if (actionType == OSNotificationAction.ActionType.ActionTaken)
Log.i("OneSignalExample", "Button pressed with id: " + result.action.actionID);
Intent intent = new Intent(mContext, PushClicked.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
Error:
er.onesignal E/AndroidRuntime: FATAL EXCEPTION: main Process: com.linkedresponder.onesignal, PID: 5680
java.lang.RuntimeException: Unable to start receiver com.onesignal.NotificationOpenedReceiver: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.app.ActivityThread.handleReceiver(ActivityThread.java:3018)
at android.app.ActivityThread.-wrap18(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1544)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.content.ComponentName.<init>(ComponentName.java:128)
at android.content.Intent.<init>(Intent.java:4868)
at com.linkedresponder.onesignal.NotificationOpenHandler.notificationOpened(NotificationOpenHandler.java:41)
at com.onesignal.OneSignal.fireNotificationOpenedHandler(OneSignal.java:1009)
at com.onesignal.OneSignal.runNotificationOpenedCallback(OneSignal.java:954)
at com.onesignal.OneSignal.handleNotificationOpen(OneSignal.java:1041)
at com.onesignal.NotificationOpenedProcessor.processIntent(NotificationOpenedProcessor.java:101)
at com.onesignal.NotificationOpenedProcessor.processFromActivity(NotificationOpenedProcessor.java:57)
at com.onesignal.NotificationOpenedReceiver.onReceive(NotificationOpenedReceiver.java:11)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:3011)
at android.app.ActivityThread.-wrap18(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1544)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Here's how I made it work:
public class MyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
OneSignal.startInit(this)
.setNotificationOpenedHandler(new MyNotificationOpenedHandler(this))
.init();
}
}
The NotificationOpenedHandler custom class
public class MyNotificationOpenedHandler implements OneSignal.NotificationOpenedHandler {
private Application application;
public MyNotificationOpenedHandler(Application application) {
this.application = application;
}
#Override
public void notificationOpened(OSNotificationOpenResult result) {
// Get custom datas from notification
JSONObject data = result.notification.payload.additionalData;
if (data != null) {
String myCustomData = data.optString("key", null);
}
// React to button pressed
OSNotificationAction.ActionType actionType = result.action.type;
if (actionType == OSNotificationAction.ActionType.ActionTaken)
Log.i("OneSignalExample", "Button pressed with id: " + result.action.actionID);
// Launch new activity using Application object
startApp();
}
private void startApp() {
Intent intent = new Intent(application, MyActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
application.startActivity(intent);
}
}
Don't forget to add this to your manifest:
<application ...>
<meta-data android:name="com.onesignal.NotificationOpened.DEFAULT" android:value="DISABLE" />
</application>
The short answer to this issue is to include your handler for the push notification open within the same class where you initialize OneSignal:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Init OneSignal
OneSignal.startInit(this).setNotificationOpenedHandler(new NotificationOpenHandler()).init();
Toolbar mToolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayUseLogoEnabled(true);
getSupportActionBar().setLogo(R.drawable.ic_launcher);
getSupportActionBar().setDisplayShowTitleEnabled(false);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new RecordingsFragment())
.commit();
}
}
class NotificationOpenHandler implements OneSignal.NotificationOpenedHandler {
// This fires when a notification is opened by tapping on it.
#Override
public void notificationOpened(OSNotificationOpenResult result) {
OSNotificationAction.ActionType actionType = result.action.type;
JSONObject data = result.notification.payload.additionalData;
String stationName = data.optString("stationName");
String timestamp = data.optString("timestamp");
String filename = data.optString("filename");
String url = getString(R.string.callResourceUrl) + filename;
Intent intent = new Intent(getApplicationContext(), CallActivity.class);
intent.putExtra("stationName", stationName);
intent.putExtra("time", timestamp);
intent.putExtra("url", url);
// intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
}
Updated code in 2022
OneSignal.NotificationOpenedHandler replaced by OneSignal.OSNotificationOpenedHandler
and result.notification.payload.additionalData replaced by result.notification.additionalData
Full code
class OneSignalNotificationOpenHandler(private val context : Context) : OneSignal.OSNotificationOpenedHandler {
override fun notificationOpened(result: OSNotificationOpenedResult?) {
if (result == null) return
val type = result.action.type
val data = result.notification.additionalData
val name = data.optString("name")
val intent = Intent(context, MainActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_REORDER_TO_FRONT or Intent.FLAG_ACTIVITY_NEW_TASK
intent.putExtra("name", name)
context.startActivity(intent)
}
}
Add it to OneSignel after OneSignal.initWithContext(this)
OneSignal.setNotificationOpenedHandler(OneSignalNotificationOpenHandler(applicationContext))
Don't forget to Add the following to your AndroidManifest.xml to prevent the launching of your main Activity
<application ...>
<meta-data android:name="com.onesignal.NotificationOpened.DEFAULT" android:value="DISABLE" />
</application>
I am developing an android project using Volley Library. Its a simple log in project. user have to enter his mobile number to see his/her details. The Project is running fine on my Emulator who's API is 23. But the main problem occurs when i run this project on lower API. My personal handset is Kitkat 4.4.4. It the project is not running on my handset.
This is my MainActivity.java
public class MainActivity extends AppCompatActivity {
EditText et_mobile;
Button buttonFind;
String get_result_url = "http://myUrl.php";
AlertDialog.Builder builder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_mobile = (EditText) findViewById(R.id.et_mobile);
buttonFind = (Button) findViewById(R.id.b_find);
builder = new AlertDialog.Builder(MainActivity.this);
buttonFind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (et_mobile.getText().toString().trim().length() == 10){
Toast.makeText(MainActivity.this, "yay", Toast.LENGTH_SHORT).show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, get_result_url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0); // since only one object is available
String code = jsonObject.getString("code");
if (code.equals("login_failed")){
displayAlertMessage("Mobile Number Miss matched",jsonObject.getString("message"));
}else{
Intent intent = new Intent(MainActivity.this,UserDetails.class);
Bundle bundle = new Bundle();
bundle.putString("user_name",jsonObject.getString("user_name"));
bundle.putString("user_address",jsonObject.getString("user_address"));
bundle.putString("user_mobile",jsonObject.getString("user_mobile"));
bundle.putString("user_notification",jsonObject.getString("user_notification"));
bundle.putString("user_status",jsonObject.getString("user_status"));
intent.putExtras(bundle);
startActivity(intent);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Error ...", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
}
)
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("user_mobile",et_mobile.getText().toString());
return params;
}
};
MySingleton.getInstance(MainActivity.this).addRequestQueue(stringRequest);
}else {
displayAlertMessage("Error ...","Input Valid Phone Number");
}
}
});
}
public void displayAlertMessage (String title, String msg){
builder.setTitle(title);
builder.setMessage(msg);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
This is SingleTon class
public class MySingleton {
private static MySingleton mInstance;
private RequestQueue requestQueue;
private static Context mCtx;
private MySingleton(Context context){
mCtx = context;
requestQueue = getRequestQueue();
}
public RequestQueue getRequestQueue(){
if (requestQueue == null){
requestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return requestQueue;
}
// this method will return instance of this class
public static synchronized MySingleton getInstance(Context context){
if (mInstance == null){
mInstance = new MySingleton(context);
}
return mInstance;
}
// this method will add requestQueue
public<T> void addRequestQueue (Request<T> request){
requestQueue.add(request);
}
}
This is the class where I can see the output
public class UserDetails extends AppCompatActivity {
TextView name, address, mobile, notification, status;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_details);
name = (TextView) findViewById(R.id.tv_user_name);
address = (TextView) findViewById(R.id.tv_user_address);
mobile = (TextView) findViewById(R.id.tv_user_mobile);
notification = (TextView) findViewById(R.id.tv_user_notification);
status = (TextView) findViewById(R.id.tv_user_status);
Bundle bundle = getIntent().getExtras();
name.setText(bundle.getString("user_name"));
address.setText(bundle.getString("user_address"));
mobile.setText(bundle.getString("user_mobile"));
notification.setText(bundle.getString("user_notification"));
status.setText(bundle.getString("user_status"));
}
This is AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.dell103.VolleyProject">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".UserDetails"></activity>
</application>
</manifest>
This is Build.gradle
defaultConfig {
applicationId "com.example.dell103.DoctorPatientVolleyProject"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.mcxiaoke.volley:library:1.0.19'
}
This is the Error showing in LogCat
09-07 16:29:39.487 20509-20509/com.example.dell103.DoctorPatientVolleyProject W/System.err: com.android.volley.NoConnectionError: java.net.UnknownHostException: http://nirjan_munshi.netne.net/VolleyDemo/json_search_result.php
09-07 16:29:39.487 20509-20509/com.example.dell103.DoctorPatientVolleyProject W/System.err: at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:158)
09-07 16:29:39.487 20509-20509/com.example.dell103.DoctorPatientVolleyProject W/System.err: at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:114)
09-07 16:29:39.491 20509-20509/com.example.dell103.DoctorPatientVolleyProject W/System.err: Caused by: java.net.UnknownHostException: http://nirjan_munshi.netne.net/VolleyDemo/json_search_result.php
09-07 16:29:39.499 20509-20509/com.example.dell103.DoctorPatientVolleyProject W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:279)
09-07 16:29:39.499 20509-20509/com.example.dell103.DoctorPatientVolleyProject W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
09-07 16:29:39.500 20509-20509/com.example.dell103.DoctorPatientVolleyProject W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
09-07 16:29:39.500 20509-20509/com.example.dell103.DoctorPatientVolleyProject W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
09-07 16:29:39.500 20509-20509/com.example.dell103.DoctorPatientVolleyProject W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:89)
09-07 16:29:39.500 20509-20509/com.example.dell103.DoctorPatientVolleyProject W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:197)
09-07 16:29:39.501 20509-20509/com.example.dell103.DoctorPatientVolleyProject W/System.err: at com.android.volley.toolbox.HurlStack.addBodyIfExists(HurlStack.java:257)
09-07 16:29:39.501 20509-20509/com.example.dell103.DoctorPatientVolleyProject W/System.err: at com.android.volley.toolbox.HurlStack.setConnectionParametersForRequest(HurlStack.java:227)
09-07 16:29:39.503 20509-20509/com.example.dell103.DoctorPatientVolleyProject W/System.err: at com.android.volley.toolbox.HurlStack.performRequest(HurlStack.java:107)
09-07 16:29:39.504 20509-20509/com.example.dell103.DoctorPatientVolleyProject W/System.err: at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:97)
09-07 16:29:39.505 20509-20509/com.example.dell103.DoctorPatientVolleyProject W/System.err: ... 1 more
09-07 16:30:45.859 20509-20509/com.example.dell103.DoctorPatientVolleyProject W/IInputConnectionWrapper: showStatusIcon on inactive InputConnection
Your error is clearly NoConnectionError caused by UnknownHostException
Try http://nirjan_munshi.netne.net/VolleyDemo/json_search_result.php in your android browser, and if you get a 404, your internet connection is the culprit! (if not look for other connectivity issues in case you are running it locally)
I am new to android.I want to build an app to receive & read emails from my own app.I prepared my code with help of these links & some blogs.
Retrieving all unread emails using javamail with POP3 protocol
https://buddhimawijeweera.wordpress.com/2011/02/09/sendreceiveemailsjava/
https://metoojava.wordpress.com/2010/03/21/java-code-to-receive-mail-using-javamailapi/
I have been working nearly for two weeks,but still app doesn't display the received emails.Please help me to find errors.Or else do you know a code to connect Gmail app with my app to receive emails ? Your any help for the app is greatly appreciated.
MailReaderActivity.java (Main Activity)
public class MailReaderActivity extends Activity{
Folder inbox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
public MailReaderActivity(){
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getDefaultInstance(props, null);
Store store;
store = session.getStore("imaps");
store.connect("imap.gmail.com","<user#gmail.com>","<password>");
inbox = store.getFolder("Inbox");
System.out.println("No of Unread Messages : " + inbox.getUnreadMessageCount());
inbox.open(Folder.READ_ONLY);
Message messages[] = inbox.search(new FlagTerm(new Flags(Flag.SEEN), false));
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.CONTENT_INFO);
inbox.fetch(messages, fp);
try {
printAllMessages(messages);
inbox.close(true);
store.close();
} catch (Exception ex) {
System.out.println("Exception arise at the time of read mail");
ex.printStackTrace();
}
} catch (NoSuchProviderException e) {
e.printStackTrace();
System.exit(1);
} catch (MessagingException e) {
e.printStackTrace();
System.exit(2);
}
}
public void printAllMessages(Message[] msgs) throws Exception
{
for (int i = 0; i < msgs.length; i++)
{
System.out.println("MESSAGE #" + (i + 1) + ":");
printEnvelope(msgs[i]);
}
}
public void printEnvelope(Message message) throws Exception
{
Address[] a;
// FROM
if ((a = message.getFrom()) != null)
{
for (int j = 0; j < 2; j++)
{
System.out.println("FROM: " + a[j].toString());
}
}
// TO
if ((a = message.getRecipients(Message.RecipientType.TO)) != null)
{
for (int j = 0; j < 2; j++)
{
System.out.println("TO: " + a[j].toString());
}
}
String subject = message.getSubject();
Date receivedDate = message.getReceivedDate();
String content = message.getContent().toString();
System.out.println("Subject : " + subject);
System.out.println("Received Date : " + receivedDate.toString());
System.out.println("Content : " + content);
getContent(message);
}
public void getContent(Message msg)
{
try
{
String contentType = msg.getContentType();
System.out.println("Content Type : " + contentType);
Multipart mp = (Multipart) msg.getContent();
int count = mp.getCount();
for (int i = 0; i < count; i++)
{
dumpPart(mp.getBodyPart(i));
}
}
catch (Exception ex)
{
System.out.println("Exception arise at get Content");
ex.printStackTrace();
}
}
public void dumpPart(Part p) throws Exception
{
// Dump input stream ..
InputStream is = p.getInputStream();
// If "is" is not already buffered, wrap a BufferedInputStream
// around it.
if (!(is instanceof BufferedInputStream))
{
is = new BufferedInputStream(is);
}
int c;
System.out.println("Message : ");
while ((c = is.read()) != -1)
{
System.out.write(c);
}
}
public static void main(String args[])
{
new MailReaderActivity();
}
}
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MailReaderActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Logcat
//01-19 13:09:00.554 8487-8487/com.example.dell.frfr E/Trace﹕ error opening trace file: No such file or directory (2)
01-19 13:09:00.812 8487-8487/com.example.dell.frfr E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.dell.frfr/com.example.dell.frfr.MailReaderActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2277)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2403)
at android.app.ActivityThread.access$600(ActivityThread.java:165)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5370)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1128)
at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getByName(InetAddress.java:289)
at java.net.InetSocketAddress.<init>(InetSocketAddress.java:105)
at java.net.InetSocketAddress.<init>(InetSocketAddress.java:90)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:321)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:237)
at com.sun.mail.iap.Protocol.<init>(Protocol.java:116)
at com.sun.mail.imap.protocol.IMAPProtocol.<init>(IMAPProtocol.java:115)
at com.sun.mail.imap.IMAPStore.newIMAPProtocol(IMAPStore.java:685)
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:636)
at javax.mail.Service.connect(Service.java:295)
at javax.mail.Service.connect(Service.java:176)
at com.example.dell.frfr.MailReaderActivity.<init>(MailReaderActivity.java:53)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1319)
at android.app.Instrumentation.newActivity(Instrumentation.java:1123)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2268)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2403)
at android.app.ActivityThread.access$600(ActivityThread.java:165)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5370)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
//
I don't know if you have already fixed this error or not, but it may help people with a similar issue if i still answer it.
In your LogCat. It says Caused by: android.os.NetworkOnMainThreadException
Android by default will not let any networking on the same thread as the rest of the application. So, to fix this we just have to simply create a new thread to run it in.
Replace:
public static void main(String args[])
{
new MailReaderActivity();
}
with this:
public static void main(String args[])
{
Thread thread = new Thread() {
#Override
public void run() {
new MailReaderActivity();
}
};
thread.start();
}
You should execute network threads asynchronously using AsyncTask. For further information read the docs.
I am trying to send GPS coordinates to server in android, but my app is crashing as soon as i run it, i am new to android so i'm not getting how to resolve this
Here is my logcat file
01-23 14:03:40.220: E/AndroidRuntime(880): FATAL EXCEPTION: main
01-23 14:03:40.220: E/AndroidRuntime(880): Process: com.example.server2, PID: 880
01-23 14:03:40.220: E/AndroidRuntime(880): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.server2/com.example.server2.MainActivity}: java.lang.IllegalArgumentException: invalid provider: null
01-23 14:03:40.220: E/AndroidRuntime(880): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
01-23 14:03:40.220: E/AndroidRuntime(880):at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
01-23 14:03:40.220: E/AndroidRuntime(880): at android.app.ActivityThread.access$800(ActivityThread.java:135)
01-23 14:03:40.220: E/AndroidRuntime(880): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
01-23 14:03:40.220: E/AndroidRuntime(880): at android.os.Handler.dispatchMessage(Handler.java:102)
01-23 14:03:40.220: E/AndroidRuntime(880): at android.os.Looper.loop(Looper.java:136)
01-23 14:03:40.220: E/AndroidRuntime(880): at android.app.ActivityThread.main(ActivityThread.java:5017)
01-23 14:03:40.220: E/AndroidRuntime(880): at java.lang.reflect.Method.invokeNative(Native Method)
01-23 14:03:40.220: E/AndroidRuntime(880): at java.lang.reflect.Method.invoke(Method.java:515)
01-23 14:03:40.220: E/AndroidRuntime(880): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
01-23 14:03:40.220: E/AndroidRuntime(880): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
01-23 14:03:40.220: E/AndroidRuntime(880): at dalvik.system.NativeStart.main(Native Method)
01-23 14:03:40.220: E/AndroidRuntime(880): Caused by: java.lang.IllegalArgumentException: invalid provider: null
01-23 14:03:40.220: E/AndroidRuntime(880): at android.location.LocationManager.checkProvider(LocationManager.java:1623)
01-23 14:03:40.220: E/AndroidRuntime(880): at android.location.LocationManager.getLastKnownLocation(LocationManager.java:1167)
01-23 14:03:40.220: E/AndroidRuntime(880): at com.example.server2.MainActivity.onCreate(MainActivity.java:71)
01-23 14:03:40.220: E/AndroidRuntime(880): at android.app.Activity.performCreate(Activity.java:5231)
01-23 14:03:40.220: E/AndroidRuntime(880): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
01-23 14:03:40.220: E/AndroidRuntime(880): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
And here is my MainActivity.java:
public class MainActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
String lat,lng;
EditText etResponse;
TextView tvIsConnected;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// get reference to the views
etResponse = (EditText) findViewById(R.id.etResponse);
tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);
// check if you are connected or not
if(isConnected()){
tvIsConnected.setBackgroundColor(0xFF00CC00);
tvIsConnected.setText("You are conncted");
}
else{
tvIsConnected.setText("You are NOT conncted");
}
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
// call AsynTask to perform network operation on separate thread
new HttpAsyncTask().execute("http://182.18.144.140:80");
}
public static String GET(String url){
InputStream inputStream = null;
String result = "";
try {
// create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// make GET request to the given URL
HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
public boolean isConnected(){
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
#Override
public void onLocationChanged(Location location) {
lat = Double.toString(location.getLatitude());
lng = Double.toString (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://182.18.144.140:80");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
// nameValuePairs.add(new BasicNameValuePair("android", editText1.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("LAT", lat));
nameValuePairs.add(new BasicNameValuePair("LON", lng));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
try {
httpclient.execute(httppost);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
Log.i("HTTP Failed", e.toString());
}
return null;
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
etResponse.setText(result);
}
}
}
And my manifest.xml is like this
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.server2"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.server2.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
provider is null. You declare it here
private String provider;
but you never initialize it properly.
This line is returning null
provider = locationManager.getBestProvider(criteria, false);
which is causing your initial exception at this line
Location location = locationManager.getLastKnownLocation(provider);
you can see that by stepping back through the stacktrace.
Debug that and see why provider is null.
i can see a couple things that might have a problem here:
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
provider is null at this point, and also you need to set the permissions to get fine or coarse user location.