Throw exception and getting e null - android

I throw a exception with some message like:
public static ILSResponseEmailLookUPBO getILSUserAccounts(Resources res,
String email) throws TripLoggerCustomException,
TripLoggerUnexpectedErrorException {
String resp = null;
String lookupURL;
try {
lookupURL = TripLoggerConstants.ServerConstants.ILS_LOOKUP_URL
+ URLEncoder.encode(email, "UTF-8");
} catch (UnsupportedEncodingException e1) {
throw new TripLoggerCustomException(
res.getString(R.string.error_try_again));
}
try {
resp = ConnectionManager.getInstance().httpRequest(lookupURL,
TripLoggerConstants.RequestMethods.GET);
} catch (IOException e) {
if (e.getMessage().equals(
res.getString(R.string.network_unreachable))
|| e.getMessage().equals(
res.getString(R.string.host_unresolved))) {
throw new TripLoggerCustomException(
res.getString(R.string.network_not_reachable));
} else {
throw new TripLoggerCustomException(
res.getString(R.string.email_notfound_ils));
}
}
here my else part execute.
And my exception class is:
public class TripLoggerCustomException extends Exception {
private String customMessage;
private static final long serialVersionUID = 1L;
public TripLoggerCustomException() {
super();
}
public TripLoggerCustomException(String message) {
super(message);
this.customMessage = (message == null ? "" : message);
}
public String getCustomMessage() {
return this.customMessage;
}
public void setCustomMessage(String customMessage) {
this.customMessage = customMessage;
}
}
And here i catch this exception:
private void manageLookUpActions(final String emailID) {
new Thread() {
public void run() {
try {
listILSAccounts = ILSLookupEmailBL.getILSUserAccounts(
getResources(), emailID);
} catch (TripLoggerCustomException e) {
dismissProgressBar();
handleException(e.getMessage());
return;
} catch (TripLoggerUnexpectedErrorException e) {
dismissProgressBar();
handleException(e.getMessage());
return;
}
}
}.start();
}
but here in catch of TripLoggerCustomException e is null.why?Can anyone help me?

After looking into multiple reports on StackOverflow, it seems like this is not an actual issue. Multiple people have been saying that it is a problem in the combination of the Eclipse debugger and the Android Emulator. That is why you don't get a NullPointerException, which you would definitely get if e was null.
So this is probably not an issue you have to worry about.

Related

How can I add Async Task in my Android Studio project?

I am new to Android and are trying to connect a mysql database to my android app, but I don't get it with the Async Task to work.
What is the best way to use Async Task in here.
Note: "name_db=readSQL1();
System.out.println(name_db+"###########################");" this prints
hier sollte name###########################
Here is my code:
b_login.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
name_db=readSQL1();
System.out.println(name_db+"###########################");
name_to_check=ed_name.getText().toString();
pw_temp=ed_pw.getText().toString();
try { pw_hash=hash(getSHA(ed_pw.getText().toString()));
} catch (NoSuchAlgorithmException e) { e.printStackTrace(); }
for(int i=0;i<user_arr.size();i++) {
if (name_to_check.equals(user_arr.get(i)) && pw_hash.equals(pw_arr.get(i))) {
startActivity(new Intent(MainActivity.this, com.example.new_app.UserMain.class).putExtra("user_name",name_to_check));
} else {
Toast.makeText(getApplicationContext(), "Wrong Credentials", Toast.LENGTH_SHORT).show();
tx_counter.setVisibility(View.VISIBLE);
tx_counter.setBackgroundColor(Color.WHITE);
counter--;
tx_counter.setText(Integer.toString(counter));
if (counter==0){
b_login.setEnabled(false);
}
}
}
}
});
b_cancel.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
finish();
}
});
}
public static String hash(byte[] hashwert){
BigInteger number=new BigInteger(1,hashwert);
StringBuilder hexString=new StringBuilder(number.toString(16));
while (hexString.length()<32) hexString.insert(0,"0");
return hexString.toString();
}
public static byte[] getSHA(String input) throws NoSuchAlgorithmException{
MessageDigest md=MessageDigest.getInstance("SHA-256");
return md.digest(input.getBytes(StandardCharsets.UTF_8));
}
public static String readSQL1(){
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
String name="hier sollte name";
try{
String url1 = "jdbc:mysql://host.de:3306/h153555_androidstudio?serverTimezone=UTC";
String user = "username"; String password = "password"; String database="user_db"; //password and username temporary
conn = DriverManager.getConnection(url1, user, password);
if (conn != null) {
stmt=conn.createStatement();
String select="SELECT NAME, PW FROM "+database;
rs=stmt.executeQuery(select);
System.out.println("read");
while(rs.next()){
name=rs.getString("NAME"); String pw=rs.getString("PW");
}
}
}catch(SQLException e){
System.out.println(e); System.out.println("read fehler");
}finally {
try { rs.close(); } catch (Exception e) { /* ignored */ }
try { stmt.close(); } catch (Exception e) { /* ignored */ }
try { conn.close(); } catch (Exception e) { /* ignored */ }
}
return name;
}
Take a look in android developers references:
https://developer.android.com/reference/android/os/AsyncTask
And you can simply use the FutureTask class
https://developer.android.com/reference/java/util/concurrent/FutureTask
You can use it this way, the Callable call function is the function that run in the task execute process.
FutureTask futureTask_1 = new FutureTask(new Callable<Integer>()
{
#Override
public Integer call() throws Exception {
return 0;
}
});
ExecutorService executor = Executors.newFixedThreadPool(1);
List<FutureTask> taskList = new ArrayList<FutureTask>();
taskList.add(futureTask_1);
executor.execute(futureTask_1);
futureTask_1.get();

Getting API Exception Wearable API is not available on this device error

I have a button in my MapsActivity that communicates to the Wear app. The following Thread is executed:
class NewThread extends Thread {
String path;
String message;
NewThread(String p, String m) {
path = p;
message = m;
}
public void run() {
Task<List<Node>> wearableList =
Wearable.getNodeClient(getApplicationContext()).getConnectedNodes();
try {
List<Node> nodes = Tasks.await(wearableList);
for (Node node : nodes) {
Task<Integer> sendMessageTask =
Wearable.getMessageClient(MapsActivity.this).sendMessage(node.getId(), path, message.getBytes());
try {
Integer result = Tasks.await(sendMessageTask);
sendmessage("I just sent the wearable a message " + sentMessageNumber++);
} catch (final ExecutionException exception) {
MapsActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toasty.error(MapsActivity.this, "[1] Something went wrong. Error details: " + exception.getMessage()).show();
}
});
} catch (final InterruptedException exception) {
MapsActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toasty.error(MapsActivity.this, "[2] Something went wrong. Error details: " + exception.getMessage()).show();
}
});
}
}
} catch (final ExecutionException exception) {
MapsActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toasty.error(MapsActivity.this, "[3] Something went wrong. Error details: " + exception.getMessage()).show();
}
});
} catch (final InterruptedException exception) {
MapsActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toasty.error(MapsActivity.this, "[4] Something went wrong. Error details: " + exception.getMessage()).show();
}
});
}
}
}
But I get the following error in the image when trying to accomplish the Thread.
This happens on an Emulator where the WearOS app/api is not available to me (Probably on real devices which do not have WearOS App/Api too).
It happens on the Wearable.getMessageClient(MapsActivity.this).sendMessage(node.getId(), path, message.getBytes());.
I didn't find a clean way of checking the Wear API to be available so I am trying to get the capabilities first, catching the ApiException and setting a isWearableAvailable property:
private fun checkCapability() {
try {
val capability = capabilityClient
.getCapability(CAPABILITY_XYZ, CapabilityClient.FILTER_REACHABLE)
.await()
isConnected = capability.nodes.any(Node::isNearby)
if (BuildConfig.DEBUG) Log.d(LOG_TAG,
"Capability: ${capability.nodes.joinToString()}} > ${isConnected}")
isWearableApiAvailable = true
} catch (e: ApiException) {
isWearableApiAvailable = false
}
}

Azure mobile service for android query table

I'm using azure sdk for android and follow the tutorial https://azure.microsoft.com/en-us/documentation/articles/mobile-services-dotnet-backend-android-get-started-data/.
When I'm trying to connect and insert data to mobile service table all is ok, but when I query the table in activity my app gets stuck, though there are only several entries in the table and execute method successfully returns Future.
public static MobileServiceClient mClient;
public static void connect(Context context) {
try {
mClient = new MobileServiceClient(storageLink, key, context);
} catch (MalformedURLException e) {
Log.e("AzureService.connect", "Storage access failed" + storageLink);
}
}
public static InstallationData get(final String deviceId) {
MobileServiceTable<InstallationData> table= mClient.getTable(InstallationData.class);
final MobileServiceList<InstallationData> result;
try {
result = table.where().field("deviceid").eq(deviceId).execute().get();
for (InstallationData item : result) {
return item;
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return null;
}
public static void store(final InstallationData item) {
mClient.getTable(InstallationData.class).insert(item, new TableOperationCallback<InstallationData>() {
public void onCompleted(InstallationData entity, Exception exception, ServiceFilterResponse response) {
if (exception == null) {
Log.d("AzureService.store()", "Data about " + item.getDeviceid() + "" + "is successfully updated");
} else {
exception.printStackTrace();
Log.e("AzureService.store()", "Data about " + item.getDeviceid() + "" + "is failed to update");
}
}
});
}
Thank you in advance!

How to get Advertising ID in android programmatically

I want to get users Advertising ID programmatically.I used the below code from the developer site.But its not working
Info adInfo = null;
try {
adInfo = AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext());
} catch (IOException e) {
// Unrecoverable error connecting to Google Play services (e.g.,
// the old version of the service doesn't support getting AdvertisingId).
} catch (GooglePlayServicesNotAvailableException e) {
// Google Play services is not available entirely.
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (GooglePlayServicesRepairableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
final String id = adInfo.getId();
final boolean isLAT = adInfo.isLimitAdTrackingEnabled();
How can I get user's advertising id programmatically ?? please help me
I might be late but this might help someone else!
AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
AdvertisingIdClient.Info idInfo = null;
try {
idInfo = AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext());
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String advertId = null;
try{
advertId = idInfo.getId();
}catch (NullPointerException e){
e.printStackTrace();
}
return advertId;
}
#Override
protected void onPostExecute(String advertId) {
Toast.makeText(getApplicationContext(), advertId, Toast.LENGTH_SHORT).show();
}
};
task.execute();
Get GAID(Google’s advertising ID)
1. Download latest Google Play Services SDK.
2. Import the code and add it as a library project.
3. Modify AndroidManifest.xml.
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
4. Enable ProGuard to shrink and obfuscate your code in project.properties this line
proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
5. Add rules in proguard-project.txt.
-keep class * extends java.util.ListResourceBundle {
protected Object[][] getContents(); }
-keep public class com.google.android.gms.common.internal.safeparcel.SafeParcelable {
public static final *** NULL; }
-keepnames #com.google.android.gms.common.annotation.KeepName class *
-keepclassmembernames class * {
#com.google.android.gms.common.annotation.KeepName *;
}
-keepnames class * implements android.os.Parcelable {
public static final ** CREATOR;
}
6. Call AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext()).getId() in a worker thread to get the id in String.
as like this
AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
AdvertisingIdClient.Info idInfo = null;
try {
idInfo = AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext());
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
String advertId = null;
try{
advertId = idInfo.getId();
}catch (Exception e){
e.printStackTrace();
}
return advertId;
}
#Override
protected void onPostExecute(String advertId) {
Toast.makeText(getApplicationContext(), advertId, Toast.LENGTH_SHORT).show();
}
};
task.execute();
Enjoy!
or
https://developervisits.wordpress.com/2016/09/09/android-2/
You can call the below function in onCreate(Bundle savedInstanceState) of the activity
and in the logcat search for UIDMY then it will display the id like : I/UIDMY: a1cf5t4e-9eb2-4342-b9dc-10cx1ad1abe1
void getUIDs()
{
AsyncTask.execute(new Runnable() {
#Override
public void run() {
try {
AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(SplashScreen.this);
String myId = adInfo != null ? adInfo.getId() : null;
Log.i("UIDMY", myId);
} catch (Exception e) {
Toast toast = Toast.makeText(context, "error occurred ", Toast.LENGTH_SHORT);
toast.setGravity(gravity, 0,0);
toast.show();
}
}
});
}
Just in case someone is interested in trying out the fetching AdvertisingId part while Rx-ing then this might be helpful.
private void fetchAndDoSomethingWithAdId() {
Observable.fromCallable(new Callable<String>() {
#Override
public String call() throws Exception {
return AdvertisingIdClient.getAdvertisingIdInfo(context).getId();
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<String>() {
#Override
public void call(String id) {
//do what you want to do with id for e.g using it for tracking
}
}, new Action1<Throwable>() {
#Override
public void call(Throwable throwable) {
throwable.printStackTrace();
}
});
}
The modern way is to use Coroutines in Kotlin, since AsyncTask is now being deprecated for Android. Here is how I did it:
import com.google.android.gms.ads.identifier.AdvertisingIdClient
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class AdvertisingInfo(val context: Context) {
private val adInfo = AdvertisingIdClient(context.applicationContext)
suspend fun getAdvertisingId(): String =
withContext(Dispatchers.IO) {
//Connect with start(), disconnect with finish()
adInfo.start()
val adIdInfo = adInfo.info
adInfo.finish()
adIdInfo.id
}
}
When you are ready to use the advertising ID, you need to call another suspending function:
suspend fun applyDeviceId(context: Context) {
val advertisingInfo = AdvertisingInfo(context)
// Here is the suspending function call,
// in this case I'm assigning it to a static object
MyStaticObject.adId = advertisingInfo.getAdvertisingId()
}
Fetch the advertising id from background thread:
AsyncTask.execute(new Runnable() {
#Override
public void run() {
try {
AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(mContext);
String adId = adInfo != null ? adInfo.getId() : null;
// Use the advertising id
} catch (IOException | GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException exception) {
// Error handling if needed
}
}
});
I added null checks to prevent any crashes. The Google example implementation code would crash with a NullPointerException if an exception occures.
With OS validation.
Call this in an AsyncTask
/** Retrieve the Android Advertising Id
*
* The device must be KitKat (4.4)+
* This method must be invoked from a background thread.
*
* */
public static synchronized String getAdId (Context context) {
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
return null;
}
AdvertisingIdClient.Info idInfo = null;
try {
idInfo = AdvertisingIdClient.getAdvertisingIdInfo(context);
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String advertId = null;
try{
advertId = idInfo.getId();
}catch (NullPointerException e){
e.printStackTrace();
}
return advertId;
}
If you are using Kotlin use this to get the Google Advertising ID of the device
CoroutineScope(Dispatchers.IO).launch {
var idInfo: AdvertisingIdClient.Info? = null
try {
idInfo = AdvertisingIdClient.getAdvertisingIdInfo(applicationContext)
} catch (e: GooglePlayServicesNotAvailableException) {
e.printStackTrace()
} catch (e: GooglePlayServicesRepairableException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
var advertId: String? = null
try {
advertId = idInfo!!.id
} catch (e: NullPointerException) {
e.printStackTrace()
}
Log.d(TAG, "onCreate:AD ID $advertId")
}
import com.google.android.gms.ads.identifier.AdvertisingIdClient.Info;
Info adInfo = null;
try {
adInfo = AdvertisingIdClient.getAdvertisingIdInfo(mContext);
} catch (IOException e) {
e.printStackTrace();
} catch (GooglePlayServicesAvailabilityException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
String AdId = adInfo.getId();
You need add gms libs otherwise you cannot get the advertising id. It can be reset by user or when you do a factory reset (at factory reset time the Android id also reset).
Make sure you have added play identity services, then you can get advertising id by running a thread like this:
Thread thread = new Thread() {
#Override
public void run() {
try {
AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext());
String advertisingId = adInfo != null ? adInfo.getId() : null;
} catch (IOException | GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException exception) {
exception.printStackTrace();
}
}
};
// call thread start for background process
thread.start();
You only need this package:
implementation("com.google.android.gms:play-services-ads-identifier:17.0.0")
It's not really listed anywhere but it's published on Mavne.
Get Google Services using
GoogleApiAvailabilityLight.getInstance
You need to run your code using Async Task
try this
Using the new Android Advertiser id inside an SDK
Using Kotlin & RxJava Observers
Import in your Gradle file
implementation 'com.google.android.gms:play-services-ads:15.0.0'
Import on top of your kotlin source file
import io.reactivex.Observable
import com.google.android.gms.ads.identifier.AdvertisingIdClient
Implement a helper function
private fun fetchAdIdAndThen(onNext : Consumer<String>, onError : Consumer<Throwable>) {
Observable.fromCallable(Callable<String> {
AdvertisingIdClient.getAdvertisingIdInfo(context).getId()
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(onNext, onError);
}
Then
fetchAdIdAndThen(Consumer<String>() {
adId ->
performMyTaskWithADID(activity, 10000, adId);
}, Consumer<Throwable>() {
throwable ->
throwable.printStackTrace();
performMyTaskWithADID(activity, 10000, "NoADID");
})

testing a class with out activity and services

this is my actual class I am writing test class below.
public class ReadFile {
private Scanner rx, tx;
public void openFile() {
try {
rx = new Scanner(new File("/sys/class/net/eth0/statistics/rx_bytes"));
tx = new Scanner(new File("/sys/class/net/eth0/statistics/tx_bytes"));
} catch (Exception e) {
e.printStackTrace();
}
}
public String readRxFile() {
String rxData = "";
while (rx.hasNext()) {
rxData = rx.next();
}
return rxData;
}
public String readTxFile() {
String txData = "";
while (tx.hasNext()) {
txData = tx.next();
}
return txData;
}
public void closeFile() {
rx.close();
tx.close();
}
}
this is test class. to test the read data.
public class Testreadrxfile extends TestCase {
public Testreadrxfile() {
super();
}
protected void setUp() throws Exception {
try {
super.setUp();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ReadFile rf;
public void testappdata() {
String str1 = rf.readRxFile();
Assert.assertEquals("14081",str1 );
}
}
this is the error I am getting.
java.lang.NullPointerException
atcom.android.deviceintelligence1. test.Testreadrxfile.testappdata(Testreadrxfile.java:26)
at java.lang.reflect.Method.invokeNative(Native Method)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:529)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1448)
this is not activity or service test to use getactivity() or getservice() so what I should do to get out of this error . thanks for help in advance.
see your code.. rf is not initialised..
ReadFile rf; // not intialisd
public void testappdata() {
String str1 = rf.readRxFile(); // equivalent to null.readRxFile();
Assert.assertEquals("14081",str1 );
}
yeah, rf is not initialised. In this kind of situation first thing to do is attach the debugger on the line you are getting error, and in most cases answer becomes obvious.
UPDATE
first your code didn't work because you didn't initialised rx, now your code doesn't work becasue you never called following function. In the function you are initialising your scanner objects. call this function from your readRxFile function and you should be good to go.
public void openFile() {
try {
rx = new Scanner(new File("/sys/class/net/eth0/statistics/rx_bytes"));
tx = new Scanner(new File("/sys/class/net/eth0/statistics/tx_bytes"));
} catch (Exception e) {
e.printStackTrace();
}
}
public String readRxFile() {
String rxData = "";
while (rx.hasNext()) { //eq. to null.haxNext()
rxData = rx.next();
}
return rxData;
}

Categories

Resources