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)
Related
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
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"/>
I am a beginner android app user. i am trying to make a BLE scanner based on a online example. however my app keep crashing and not working at all. can anyone please help me identify the problem?
I have looked into various online solutions. the example i am following is this:
https://github.com/kaviles/BLE_Tutorials
this is my manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ble_scanner">
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
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>
</application>
</manifest>
here is my MainActivity:
public class MainActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener {
private final static String TAG = MainActivity.class.getSimpleName();
public static final int REQUEST_ENABLE_BT = 1;
private HashMap<String, BTLE_Device> mBTDevicesHashMap;
private ArrayList<BTLE_Device> mBTDevicesArrayList;
private ListAdapter_BTLE_Devices adapter;
private Button btn_Scan;
private BroadcastReceiver_BTState mBTStateUpdateReceiver;
private Scanner_BTLE mBTLeScanner;
private static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkLocationPermission();
if(!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)){
Utils.toast(getApplicationContext(),"BLE not supported");
finish();
}
mBTStateUpdateReceiver = new BroadcastReceiver_BTState(getApplicationContext());
mBTLeScanner = new Scanner_BTLE(this,7500,-75);
mBTDevicesHashMap = new HashMap<>();
mBTDevicesArrayList = new ArrayList<>();
adapter = new ListAdapter_BTLE_Devices(this, R.layout.btle_device_list_item, mBTDevicesArrayList);
ListView listView = new ListView(this);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
btn_Scan = (Button) findViewById(R.id.btn_scan);
((ScrollView) findViewById(R.id.scrollView)).addView(listView);
findViewById(R.id.btn_scan).setOnClickListener(this);
}
#Override
protected void onStart(){
super.onStart();
registerReceiver(mBTStateUpdateReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
}
#Override
protected void onResume(){
super.onResume();
}
#Override
protected void onPause(){
super.onPause();
stopScan();
}
protected void onStop(){
super.onStop();
unregisterReceiver(mBTStateUpdateReceiver);
startScan();
}
#Override
protected void onDestroy(){
super.onDestroy();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if (requestCode == REQUEST_ENABLE_BT){
if (resultCode == RESULT_OK){
Utils.toast(getApplicationContext(),"Bluetooth is ready to use");
}
else if (resultCode == RESULT_CANCELED){
Utils.toast(getApplicationContext(),"Please turn on Bluetooth");
}
}
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_scan:
Utils.toast(getApplicationContext(),"Scan button pressed");
if(!mBTLeScanner.isScanning()){
startScan();
} else {
startScan();
}
break;
default:
break;
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
public void addDevice(BluetoothDevice device, int new_rssi) {
String address = device.getAddress();
if(!mBTDevicesHashMap.containsKey(address)){
BTLE_Device btle_device = new BTLE_Device(device);
btle_device.setRssi(new_rssi);
mBTDevicesHashMap.put(address, btle_device);
mBTDevicesArrayList.add(btle_device);
} else {
mBTDevicesHashMap.get(address).setRssi(new_rssi);
}
adapter.notifyDataSetChanged();
}
public void startScan(){
btn_Scan.setText("Scanning...");
mBTDevicesArrayList.clear();
mBTDevicesHashMap.clear();
adapter.notifyDataSetChanged();
mBTLeScanner.start();
}
public void stopScan() {
btn_Scan.setText("Scan Again");
mBTLeScanner.stop();
}
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
new AlertDialog.Builder(this)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
onResume();
}
} else {
onDestroy();
}
return;
}
}
}
}
Here is the logcat:
2019-07-16 14:45:14.758 26071-26071/com.example.ble_scanner I/ple.ble_scanne: Not late-enabling -Xcheck:jni (already on)
2019-07-16 14:45:14.837 26071-26071/com.example.ble_scanner W/ple.ble_scanne: Unexpected CPU variant for X86 using defaults: x86
2019-07-16 14:45:14.935 26071-26079/com.example.ble_scanner E/ple.ble_scanne: Failed to send DDMS packet REAQ to debugger (-1 of 20): Broken pipe
2019-07-16 14:45:15.164 26071-26071/com.example.ble_scanner W/ple.ble_scanne: JIT profile information will not be recorded: profile file does not exits.
2019-07-16 14:45:15.166 26071-26071/com.example.ble_scanner I/chatty: uid=10096(com.example.ble_scanner) identical 10 lines
2019-07-16 14:45:15.166 26071-26071/com.example.ble_scanner W/ple.ble_scanne: JIT profile information will not be recorded: profile file does not exits.
2019-07-16 14:45:15.215 26071-26071/com.example.ble_scanner I/InstantRun: starting instant run server: is main process
2019-07-16 14:45:15.610 26071-26071/com.example.ble_scanner W/ple.ble_scanne: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (light greylist, reflection)
2019-07-16 14:45:15.612 26071-26071/com.example.ble_scanner W/ple.ble_scanne: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (light greylist, reflection)
2019-07-16 14:45:15.824 26071-26071/com.example.ble_scanner E/BluetoothAdapter: Bluetooth binder is null
2019-07-16 14:45:15.831 26071-26071/com.example.ble_scanner D/AndroidRuntime: Shutting down VM
2019-07-16 14:45:15.834 26071-26071/com.example.ble_scanner E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ble_scanner, PID: 26071
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ble_scanner/com.example.ble_scanner.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ScrollView.addView(android.view.View)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ScrollView.addView(android.view.View)' on a null object reference
at com.example.ble_scanner.MainActivity.onCreate(MainActivity.java:65)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
In your xml layout try to check if the id of ScrollView is "scrollView", if not change it to scrollView the same as how you initialize in this line.
((ScrollView) findViewById(R.id.scrollView)).addView(listView);
or check your xml layout if ScrollView widget exist.
It throws the null pointer Exception because it cannot bind the layout, the id maybe misspelled or there is no scrollview widget in your layout.
Thank you everyone for your suggestion. The issue is solved. this code has two issue for which it did not work.
1. ((ScrollView) findViewById(R.id.scrollView)).addView(listView);
in this line scrollView is the wrong ID name. it should be the ID of your scrollview which for my case is device_list. it was making the app crash.
second issue is that i didnot call call for the permission function which will not give the list of BLE devices for android 6+ devices.
MANIFEST:(partial view)
MainActivity, program immediately terminates and issues the messages in the Log.
It should have started showing the buttons to select options to continue execution.
After days of researching this forum, I found postings that suggest to place the BackupDb inside the application in the Manifest.
After doing that, I ended up with the message in the log.
Having exhausted my research venues, I'd like to know what could be the problem and how to solve it.
MANIFEST:(partial view)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.peter.databasetest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<supports-screens
android:xlargeScreens="true"
android:largeScreens="true"
android:normalScreens="true"
android:smallScreens="false"
/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
**android:name="com.peter.databasetest.BackupDB">**
<activity
android:name="com.peter.databasetest.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>
<activity
android:name=".CheckDatabase"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.CHECKDATABASE" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".CheckSDcard"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.CHECKSDCARD" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.peter.databasetest.Insert"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.peter.databasetest.INSERT" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity: Calls checkSDcard and CheckDatabase. Checks if there is SDCard present and the database in main, exists.
public class MainActivity extends Activity implements OnClickListener {
DBAdapter db;
Button insertButton; //ADD A NEW RECORD
Button listAllButton; //LIST ALL
Button cancelButton; //CANCEL PGM
Button backupDbButton; //REQUEST BACKUP DB TO SDCARD
Button restoreButton; //RESTORE DB FROM SDCARD TO MAIN
Button memsizeButton; //SHOW MEMORY SIZES ON DEVICE
int retcode;
int chk;
String message;
public Context context;
public static final String NO_DB ="Database does not exist. Backup is not possible";
public static final String DB_PB ="ERROR- Check log";
public static final String UNWR_SDCARD ="Your SDCard must be set to writable. Check the card lock";
public static final String NO_SDCARD ="No SDcard detected. No backup is possible";
public static final String BKP_OK = "Backup was SUCCESSFUL.";
public static final String BKP_NOK = "Backup FAILED. ";
static final int SD_CHECK = 1;
static final int DB_CHECK = 2;
static final int BK_CHECK = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
insertButton = (Button) findViewById(R.id.insertButton);
listAllButton = (Button) findViewById(R.id.listAllButton);
cancelButton = (Button) findViewById(R.id.cancelButton);
backupDbButton = (Button) findViewById(R.id.backupDbButton);
restoreButton = (Button) findViewById(R.id.restoreButton);
memsizeButton = (Button) findViewById(R.id. memsizeButton);
insertButton.setOnClickListener(this); //insert record into DB
listAllButton.setOnClickListener(this); //list ALL records from DB
cancelButton.setOnClickListener(this); //cancel the program
backupDbButton.setOnClickListener(this); //request backup to sdcard
restoreButton.setOnClickListener(this); //request restore from sdcard
memsizeButton.setOnClickListener(this); //Get Meory sizes
public void onClick(View v ) {
if (v == insertButton) {
startActivity(new Intent(getApplicationContext(), Insert.class));
}else if (v == listAllButton){
startActivity (new Intent(MainActivity.this, ListDr.class));
}else if (v == backupDbButton){
**Intent checksd = new Intent(this,CheckSDcard.class);**
**startActivityForResult(checksd, SD_CHECK);**
}else if (v == restoreButton) {
startActivity (new Intent(MainActivity.this,RestoreDB.class));
}else if (v == memsizeButton) {
startActivity (new Intent(MainActivity.this,GetMemorySizes.class));
}else if (v == cancelButton){
finish();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SD_CHECK && resultCode == RESULT_OK) {
Intent checkdb = new Intent(MainActivity.this,CheckDatabase.class);
startActivityForResult(checkdb, DB_CHECK);
}else if (requestCode == DB_CHECK && resultCode == RESULT_OK){
**Intent backup = new Intent(MainActivity.this,BackupDB.class);**
**startActivityForResult(backup, BK_CHECK);**
}else if (requestCode == BK_CHECK && resultCode == RESULT_OK){
message = BKP_OK;
SendMessageDialog(message);
finish();
}
if(resultCode == RESULT_CANCELED && resultCode == -1){
message = NO_DB;
SendMessageDialog(message);
finish();
}else if(resultCode == RESULT_CANCELED && resultCode == -2) {
message = DB_PB;
SendMessageDialog(message);
finish();
}
}
BackupDb: Copies the database to the SDCARD.
package com.peter.databasetest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import com.peter.databasetest.DBAdapter;
public class BackupDB extends AsyncTask<Void, Void, Integer> {
DBAdapter db;
intrc= -10;
intretcode;
intchk;
Stringmessage;
String mypackage;
public Context context;
public static String FOLDER_NAME = "DBfolder";
public static final String DATABASE_NAME = "UserDB.db";
public static final String DATABASE_BACKUP= "UserDB.db";
public static final String BKP_OK = "Backup was SUCCESSFUL.";
public static final String BKP_NOK = "Backup FAILED. ";
#Override
protected void onPreExecute() {
// GET PACKAGE NAME
mypackage = context.getApplicationContext().getPackageName() ;
}
// START BACKUP TO SDCARD
#Override
protected Integer doInBackground(Void... params) {
// DOING BACKUP
Log.i("00000" , "STARTING BACKUP...BACKUP ");
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
CREATE A FOLDER /mnt/sdcard<packagename>FOLDER_NAME if it does not exist
File folder = new File(Environment.getExternalStorageDirectory()
+ "/"
+ mypackage
+ "/"
+ FOLDER_NAME);
if(!folder.exists()) {
if (folder.mkdirs()) ;
}
// GET THE PATH OF THE BACKUP ON THE SDCARD
FilefileBackupDir = new File(Environment.getExternalStorageDirectory()
+ "/"
+mypackage
+ "/"
+ FOLDER_NAME
+"/"
+ DATABASE_BACKUP) ;
// IF WE HAVE A BACKUP ON SDCARD, DELETE IT TO MAKE ROOM FOR THE NEW BACKUP
if (fileBackupDir.exists()) {
fileBackupDir.delete();
}else {
* DO NOTHING */
}
// GET CURRENT DB PATH FOR THE COPY
String currentDBPath = "/data/" + mypackage + "/databases/"+ DATABASE_NAME;
// GET CURRENT DB PATH FOR THE BACKUP
String backupDBPath = "/" + mypackage + "/" +FOLDER_NAME + "/" + DATABASE_BACKUP;
FilecurrDB = new File(data, currentDBPath) ;
FilebkpDB = new File(sd, backupDBPath);
FileChannel from = null;
try {
from = new FileInputStream(currDB).getChannel();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
FileChannel to = null;
try {
to = new FileOutputStream(bkpDB).getChannel();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
to.transferFrom(from, 0, from.size());
} catch (IOException e) {
e.printStackTrace();
}
try {
from.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
to.close();
} catch (IOException e) {
e.printStackTrace();
}
retcode = 0;
returnretcode;
// end DoInBackgroung
protectedvoid onPostExecute(Integer retcode, String message) {
if(retcode == 0) {
message = BKP_OK;
SendMessageDialog(message);
}else {
message = BKP_NOK;
SendMessageDialog(message);
}
}
public void SendMessageDialog(String message) {
if (message == BKP_OK ) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("My Database")
.setMessage(message) // Title of the dialog
.setCancelable(true) // Does allow the use of Back Button on the hardware
.setIcon(R.drawable.ecg)// da picture
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}else {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("My Database")
.setMessage(message) // Title of the dialog
.setCancelable(true) // Does allow the use of Back Button on the hardware
.setIcon(R.drawable.bad)// da picture
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
}
}
Logcat:
02-12 07:36:06.015: E/AndroidRuntime(987): FATAL EXCEPTION: main
02-12 07:36:06.015: E/AndroidRuntime(987): java.lang.RuntimeException: Unable to instantiate application com.peter.databasetest.BackupDB:
: com.peter.databasetest.BackupDB cannot be cast to android.app.Application
02-12 07:36:06.015: E/AndroidRuntime(987): at android.app.LoadedApk.makeApplication(LoadedApk.java:501)
02-12 07:36:06.015: E/AndroidRuntime(987): at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4124)
02-12 07:36:06.015: E/AndroidRuntime(987): at android.app.ActivityThread.access$1300(ActivityThread.java:130)
02-12 07:36:06.015: E/AndroidRuntime(987): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1255)
02-12 07:36:06.015: E/AndroidRuntime(987): at android.os.Handler.dispatchMessage(Handler.java:99)
02-12 07:36:06.015: E/AndroidRuntime(987): at android.os.Looper.loop(Looper.java:137)
02-12 07:36:06.015: E/AndroidRuntime(987): at android.app.ActivityThread.main(ActivityThread.java:4745)
02-12 07:36:06.015: E/AndroidRuntime(987): at java.lang.reflect.Method.invokeNative(Native Method)
02-12 07:36:06.015: E/AndroidRuntime(987): at java.lang.reflect.Method.invoke(Method.java:511)
02-12 07:36:06.015: E/AndroidRuntime(987): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
02-12 07:36:06.015: E/AndroidRuntime(987): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
02-12 07:36:06.015: E/AndroidRuntime(987): at dalvik.system.NativeStart.main(Native Method)
02-12 07:36:06.015: E/AndroidRuntime(987): Caused by: java.lang.ClassCastException: com.peter.databasetest.BackupDB cannot be cast to android.app.Application
02-12 07:36:06.015: E/AndroidRuntime(987): at android.app.Instrumentation.newApplication(Instrumentation.java:982)
02-12 07:36:06.015: E/AndroidRuntime(987): at android.app.Instrumentation.newApplication(Instrumentation.java:967)
02-12 07:36:06.015: E/AndroidRuntime(987): at android.app.LoadedApk.makeApplication(LoadedApk.java:496)
02-12 07:36:06.015: E/AndroidRuntime(987): ... 11 more
Comment:
I removed the BackupDb from the application and reinstated it as activity.
<activity
android:name=".BackupDB"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.peter.databasetest.BACKUPDB" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
The program now brings up the buttons as expected, but when trying the backup I still get the same message as in the earlier log. (Catch-22?)
Most current log:
02-12 13:00:16.569: W/dalvikvm(30656): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
02-12 13:00:16.650: E/AndroidRuntime(30656): FATAL EXCEPTION: main
02-12 13:00:16.650: E/AndroidRuntime(30656): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.peter.databasetest/com.peter.databasetest.BackupDB}: java.lang.ClassCastException: com.peter.databasetest.BackupDB cannot be cast to android.app.Activity
02-12 13:00:16.650: E/AndroidRuntime(30656): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
02-12 13:00:16.650: E/AndroidRuntime(30656): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
02-12 13:00:16.650: E/AndroidRuntime(30656): at android.app.ActivityThread.access$600(ActivityThread.java:130)
02-12 13:00:16.650: E/AndroidRuntime(30656): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
02-12 13:00:16.650: E/AndroidRuntime(30656): at android.os.Handler.dispatchMessage(Handler.java:99)
02-12 13:00:16.650: E/AndroidRuntime(30656): at android.os.Looper.loop(Looper.java:137)
02-12 13:00:16.650: E/AndroidRuntime(30656): at android.app.ActivityThread.main(ActivityThread.java:4745)
02-12 13:00:16.650: E/AndroidRuntime(30656): at java.lang.reflect.Method.invokeNative(Native Method)
02-12 13:00:16.650: E/AndroidRuntime(30656): at java.lang.reflect.Method.invoke(Method.java:511)
02-12 13:00:16.650: E/AndroidRuntime(30656): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
02-12 13:00:16.650: E/AndroidRuntime(30656): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
02-12 13:00:16.650: E/AndroidRuntime(30656): at dalvik.system.NativeStart.main(Native Method)
02-12 13:00:16.650: E/AndroidRuntime(30656): Caused by: java.lang.ClassCastException: com.peter.databasetest.BackupDB cannot be cast to android.app.Activity
02-12 13:00:16.650: E/AndroidRuntime(30656): at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
02-12 13:00:16.650: E/AndroidRuntime(30656): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
02-12 13:00:16.650: E/AndroidRuntime(30656): ... 11 more
>Question:
>Is there any known limitation calling an AsyncTask by way of startActivityForResult?
>Could this be a factor?
The problem is in the Manifest file, you are setting your application:name to be te BackupDB class and this class is only an AsyncTask not an Application.
As can be seen on the explanation of "android:name":
An optional name of a class implementing the overall
android.app.Application for this package. [string]
I would like to take user input entered in the EditTextField(in the EnterNewFile class) and put it into the TextField (in the NoteEdit class). Please help! Thanks! FYI- I use XML files for the layouts of these two classes.
***********EnterNewFile.class*********
package com.example.note;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class EnterNewFile extends Activity {
public EditText mText;
public Button mButton;
public final static String EXTRA_MESSAGE = "com.example.note.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.new_file_start);
mText = (EditText)findViewById(R.id.file_name_edittext);
mButton = (Button)findViewById(R.id.next_button);
}
public void nextButton(View view)
{
/** Called when the user clicks the Next button */
Log.d("EditText", mText.getText().toString());
mText.getText().toString();
Intent intent = new Intent(this, NoteEdit.class);
EditText editText = (EditText) findViewById(R.id.file_name_edittext);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
//
}
}
******************************************
********NoteEdit.class************
package com.example.note;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class NoteEdit extends Activity{
public static int numTitle = 1;
public static String curDate = "";
public static String curText = "";
private TextView mTitleText;
private EditText mBodyText;
private TextView mDateText;
private Long mRowId;
private Cursor note;
private NotesDbAdapter mDbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDbHelper = new NotesDbAdapter(this);
mDbHelper.open();
setContentView(R.layout.note_edit_add);
setTitle(R.string.app_name);
mTitleText = (TextView) findViewById(R.id.title);
mBodyText = (EditText) findViewById(R.id.body);
mDateText = (TextView) findViewById(R.id.notelist_date);
long msTime = System.currentTimeMillis();
Date curDateTime = new Date(msTime);
SimpleDateFormat formatter = new SimpleDateFormat("M'/'d'/'y");
curDate = formatter.format(curDateTime);
mDateText.setText(""+curDate);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(EnterNewFile.EXTRA_MESSAGE);
// Create the text view
// TextView textView = new TextView(this);
mTitleText.setText(message);
// Set the text view as the activity layout
// setContentView(textView);
// mTitleText.setText(dana);
mRowId = (savedInstanceState == null) ? null :
(Long) savedInstanceState.getSerializable(NotesDbAdapter.KEY_ROWID);
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? extras.getLong(NotesDbAdapter.KEY_ROWID)
: null;
}
populateFields();
}
public void addFiles(View view)
{
/*Intent addFilesTarget = new Intent(this, Welcome.class);
startActivity(addFilesTarget);*/
}
public static class LineEditText extends EditText{
// we need this constructor for LayoutInflater
public LineEditText(Context context, AttributeSet attrs) {
super(context, attrs);
mRect = new Rect();
mPaint = new Paint();
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
mPaint.setColor(Color.BLUE);
}
private Rect mRect;
private Paint mPaint;
#Override
protected void onDraw(Canvas canvas) {
int height = getHeight();
int line_height = getLineHeight();
int count = height / line_height;
if (getLineCount() > count)
count = getLineCount();
Rect r = mRect;
Paint paint = mPaint;
int baseline = getLineBounds(0, r);
for (int i = 0; i < count; i++) {
canvas.drawLine(r.left, baseline + 1, r.right, baseline + 1, paint);
baseline += getLineHeight();
super.onDraw(canvas);
}
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveState();
outState.putSerializable(NotesDbAdapter.KEY_ROWID, mRowId);
}
#Override
protected void onPause() {
super.onPause();
saveState();
}
#Override
protected void onResume() {
super.onResume();
populateFields();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.noteedit_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_about:
/* Here is the intro about myself */
AlertDialog.Builder dialog = new AlertDialog.Builder(NoteEdit.this);
dialog.setTitle("About");
dialog.setMessage("Hello! I'm Dana, creator of this application. This is for documenting research."
+"\n melaninabeauty#gmail.com");
dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
dialog.show();
return true;
case R.id.menu_delete:
if(note != null){
note.close();
note = null;
}
if(mRowId != null){
mDbHelper.deleteNote(mRowId);
}
finish();
return true;
case R.id.menu_save:
saveState();
finish();
default:
return super.onOptionsItemSelected(item);
}
}
private void saveState() {
String title = mTitleText.getText().toString();
String body = mBodyText.getText().toString();
if(mRowId == null){
mDbHelper.createNote(title, body, curDate);
}else{
mDbHelper.updateNote(mRowId, title, body, curDate);
}
}
private void populateFields() {
if (mRowId != null) {
note = mDbHelper.fetchNote(mRowId);
startManagingCursor(note);
mTitleText.setText(note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
mBodyText.setText(note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY)));
curText = note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY));
}
}
}
***********************************
****AndroidManifest.xml****
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.note"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.note.Welcome"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.note.NoteList">
</activity>
<activity
android:name="com.example.note.NoteEdit">
</activity>
<activity
android:name="com.example.note.Export">
</activity>
<activity
android:name="com.example.note.NoteEditAdd">
</activity>
<activity
android:name="com.example.note.EnterNewFile">
</activity>
</application>
</manifest>
<!--
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.note"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity android:name="com.example.note.Welcome">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.note.NoteList"
android:label="#string/app_name" >
</activity>
<activity
android:name="com.example.note.NoteEdit"
android:label="#string/edit_note"
android:parentActivityName="com.example.note.Welcome" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.note.Welcome" />
</activity>
</application>
</manifest>
-->
<!--
activity 2 android:name= com.example.note.NoteEdit
android:label=#string/app_name
android:windowSoftInputMode="djustUnspecified/>
-->
*****************************
> *****LogCat of crash**** Crash occurs after nextButton is clicked****(I inputted the text "nouy", clicked nextButton, then application crashes.********************
LogCat of crash** Crash occurs after nextButton is clicked*(I inputted the text "nouy", clicked nextButton, then application crashees.**
08-02 20:48:36.703: D/EditText(3575): nouy
08-02 20:48:36.793: I/Choreographer(3575): Skipped 68 frames! The application may be doing too much work on its main thread.
08-02 20:48:37.143: D/dalvikvm(3575): GC_CONCURRENT freed 1331K, 34% free 2956K/4428K, paused 4ms+59ms, total 137ms
08-02 20:48:37.353: D/AndroidRuntime(3575): Shutting down VM
08-02 20:48:37.394: W/dalvikvm(3575): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
08-02 20:48:37.443: E/AndroidRuntime(3575): FATAL EXCEPTION: main
08-02 20:48:37.443: E/AndroidRuntime(3575): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.note/com.example.note.NoteEdit}: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
08-02 20:48:37.443: E/AndroidRuntime(3575): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
08-02 20:48:37.443: E/AndroidRuntime(3575): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
08-02 20:48:37.443: E/AndroidRuntime(3575): at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-02 20:48:37.443: E/AndroidRuntime(3575): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
08-02 20:48:37.443: E/AndroidRuntime(3575): at android.os.Handler.dispatchMessage(Handler.java:99)
08-02 20:48:37.443: E/AndroidRuntime(3575): at android.os.Looper.loop(Looper.java:137)
08-02 20:48:37.443: E/AndroidRuntime(3575): at android.app.ActivityThread.main(ActivityThread.java:5041)
08-02 20:48:37.443: E/AndroidRuntime(3575): at java.lang.reflect.Method.invokeNative(Native Method)
08-02 20:48:37.443: E/AndroidRuntime(3575): at java.lang.reflect.Method.invoke(Method.java:511)
08-02 20:48:37.443: E/AndroidRuntime(3575): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-02 20:48:37.443: E/AndroidRuntime(3575): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-02 20:48:37.443: E/AndroidRuntime(3575): at dalvik.system.NativeStart.main(Native Method)
08-02 20:48:37.443: E/AndroidRuntime(3575): Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
08-02 20:48:37.443: E/AndroidRuntime(3575): at android.database.AbstractCursor.checkPosition(AbstractCursor.java:424)
08-02 20:48:37.443: E/AndroidRuntime(3575): at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
08-02 20:48:37.443: E/AndroidRuntime(3575): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
08-02 20:48:37.443: E/AndroidRuntime(3575): at com.example.note.NoteEdit.populateFields(NoteEdit.java:231)
08-02 20:48:37.443: E/AndroidRuntime(3575): at com.example.note.NoteEdit.onCreate(NoteEdit.java:99)
08-02 20:48:37.443: E/AndroidRuntime(3575): at android.app.Activity.performCreate(Activity.java:5104)
08-02 20:48:37.443: E/AndroidRuntime(3575): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
08-02 20:48:37.443: E/AndroidRuntime(3575): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
08-02 20:48:37.443: E/AndroidRuntime(3575): ... 11 more
08-02 20:48:40.073: E/Trace(3598): error opening trace file: No such file or directory
(2)
Take the input from Edittext send it through the Intent to your destination activity and then set it in the TextView there.
I think you seem to already be doing that in your code:
The issue might be the you've not defined in your XML that nextButton function should be call on click ( inside android:onClick: inside your Button).
What you can also do is, in your onCreate funcion set up a listener which listens to the button click and call the intent from within it.
final EditText editText = (EditText) findViewById(R.id.file_name_edittext);
mButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/** Called when the user clicks the Next button */
Log.d("EditText", mText.getText().toString());
Intent intent = new Intent(EnterNewFile.this, NoteEdit.class);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
});
//here you are taking value from EditText and send it to other activity:
Instead of
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(EnterNewFile.EXTRA_MESSAGE);
use following in onCreate() of your other NoteEdit activity:
Intent intent = getIntent();
if((intent.getExtras()!=null) && !intent.getExtras().isEmpty()){
String message = intent.getExtras().getString(EnterNewFile.EXTRA_MESSAGE);
}
this code is working:-
scrollview=(ScrollView)findViewById(R.id.scrollview1);
tb2.setTextSize(30);
tb2.setMovementMethod(new ScrollingMovementMethod());
scrollview.post(new Runnable() {
public void run() {
scrollview.fullScroll(View.FOCUS_DOWN);
}
});
chat1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
{
textsaring1=edt1.getText().toString();
tb2.setText(tb2.getText()+" "+textsaring1);
edt1.setText("");
}
}
});