Android URLEncoder.encode unhandled exception java.io.UnsupportedEncodingException - java

I try to implement Android searchable and I want to filter query, I follow this link, this, and others. but in Android Studio I got this message unhandled exception java.io.UnsupportedEncodingException, this is my code
import java.net.URLEncoder;`
private void doSearch(String queryStr) {
// get a Cursor, prepare the ListAdapter
// and set it
//Log.e("Query",queryStr);
searchRestaurants(URLEncoder.encode(queryStr, "UTF-8"));}

You need to wrap your URLEncoder.encode()-method in a try-catch block:
try {
URLEncoder.encode(queryStr, "UTF-8");
} catch (UnsupportedEncodingException e) {
Log.e("Yourapp", "UnsupportedEncodingException");
}
The reason you're getting this error is that some platforms might not support UTF-8 encoding. Android definitely does, so you'll never receive this Exception, but you still need to handle it to make the compiler happy.
However, your code won't do anything, you'll need to store the result of the encode()-operation in a variable, e.g. String myEncodedQuery = URLEncoder.encode(queryStr, "UTF-8");.

import java.net.URLEncoder;
private void doSearch(String queryStr) {
// get a Cursor, prepare the ListAdapter
// and set it
//Log.e("Query",queryStr);
try {
final String encodedPath = URLEncoder.encode(queryStr, "UTF-8"));
searchRestaurants(encodedPath);
} catch (UnsupportedEncodingException ec) {
Log.d(TAG, ec.printStacktrace);
}
}

Related

Malformed PDF print doesn't catch RuntimeException

I try to print a PDF file and it works fine until I try to print a malformed PDF file.
I don't know why the application crashes even though I used try / catch to prevent crashes. I checked and found out that PrintManager.java:1101 throws RuntimeException:
case MSG_ON_KILL: {
if (DEBUG) {
Log.i(LOG_TAG, "onKill()");
}
String reason = (String) message.obj;
throw new RuntimeException(reason);
}
so code below shouldn't lead to crash:
public static void startPdfPrintProcedure(#NonNull Context context, #NonNull String filePath, #Nullable String jobName) {
try {
PrintManager printManager = (PrintManager) context.getSystemService(Context.PRINT_SERVICE);
String jobName = formatDefaultJobName(context.getResources(), jobName);
PrintDocumentAdapter pda = new SimplePrintDocumentAdapter(new File(filePath));
if (printManager != null) {
try {
printManager.print(jobName, pda, null); // <- crash here even though there is a try/catch
} catch (RuntimeException e) {
showUnknownError();
}
} else {
showUnknownError();
}
} catch (RuntimeException e) {
showUnknownError();
}
}
Exception that I get after try to print PDF. :
java.lang.RuntimeException: Cannot print a malformed PDF file
at android.print.PrintManager$PrintDocumentAdapterDelegate$MyHandler.handleMessage(PrintManager.java:1101)
at android.os.Handler.dispatchMessage(Handler.java:112)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7625)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
Why try/catch code doesn't catch this exception? How can I secure this piece of code from crashing?
This happens because some "Genius" Google developer has come up with the "Great" idea of throwing an exception in the main thread causing your application to close.
I have tried to solve the problem using reflection but the implementation is too closed.
Unfortunately, you have to use it assuming the imminent closure of your application in case of incorrect files, unless you want to implement a library to check the PDF format before calling the API.
Google never fails, you always have to mess around with its implementation.
The secondary thread ends up calling this handler.
private final class MyHandler extends Handler {
public static final int MSG_ON_KILL = 5;
...
#Override
public void handleMessage(Message message) {
switch (message.what) {
...
case MSG_ON_KILL: {
if (DEBUG) {
Log.i(LOG_TAG, "onKill()");
}
String reason = (String) message.obj;
throw new RuntimeException(reason);<---------
}
default: {
throw new IllegalArgumentException("Unknown message: "
+ message.what);
}
}
}
}
One way is to check if PDF file is corrupted or not by using PDF viewer library : https://github.com/voghDev/PdfViewPager
import library : implementation 'es.voghdev.pdfviewpager:library:1.1.2'
Use below code to check if PDF file is corrupted
BasePDFPagerAdapter adapter;
PDFViewPager pdfViewPager;
pdfViewPager = findViewById(R.id.pdfViewPager);
adapter = new PDFPagerAdapter(this, path, new PdfErrorHandler() {
#Override
public void onPdfError(Throwable t) {
Log.d("pdfcorrupt",">> yes");
isPDFCorrupted = true;
}
});
pdfViewPager.setAdapter(adapter);
When PDF file is not valid, onPdfError() method will be called.
If your file is corrupted, simply do not allow to print.

FirebaseVisionImage: variable 'image' might not have been initialized

I'm trying to use the example for Google Firebase (machine learning kit) in Android Studio. I'm getting an error when passing the image variable into the detector.processImage method (error shown below).
How can I get past this error? I have to use the FirebaseVisionImage.fromFilePath within a try-catch block, but the error message is telling me that the image variable may not be initialized.
error: variable image might not have been initialized
FirebaseVisionImage image;
try {
image = FirebaseVisionImage.fromFilePath(MainMenuActivity.this,
Uri.fromFile(new File("/sdcard/Download/test.jpg")));
} catch (IOException e) {
e.printStackTrace();
}
FirebaseVisionTextRecognizer detector = FirebaseVision.getInstance().getOnDeviceTextRecognizer();
Task<FirebaseVisionText> result = detector.processImage(image)
.addOnSuccessListener(new OnSuccessListener<FirebaseVisionText>() {
#Override
public void onSuccess(FirebaseVisionText firebaseVisionText) {
// Task completed successfully
mainText.setText("Hello!");
}
})
.addOnFailureListener(
new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// Task failed with an exception
}
}
);
That error emerges because of this piece of code
FirebaseVisionImage image;
try {
image = FirebaseVisionImage.fromFilePath(
MainMenuActivity.this,
Uri.fromFile(new File("/sdcard/Download/test.jpg"))
);
} catch (IOException e) {
e.printStackTrace();
}
Now, ask yourself, what happens to image if an Exception is thrown inside the try block?
The variable might have been assigned a valid value, or it might have not.
Because you're letting the execution flow to continue (you aren't throwing the Exception to the upper level), the compiler cannot know that for sure, since the exception is thrown at run-time.
And because in Java a local variable must be initialized before usage (even with = null), the compiler is telling you to do so.
error: variable image might not have been initialized
The solution might be to initialize it with null
FirebaseVisionImage image = null;
Or, a better one, to let escape the Exception. That will signal there is a bug.
You'll also be able to completely unwrap your code from the try - catch block.
All code that needs the image should be inside the try block:
try {
FirebaseVisionImage image = FirebaseVisionImage.fromFilePath(MainMenuActivity.this,
Uri.fromFile(new File("/sdcard/Download/test.jpg")));
Task<FirebaseVisionText> result = detector.processImage(image)
.addOnSuccessListener(new OnSuccessListener<FirebaseVisionText>() {
#Override
public void onSuccess(FirebaseVisionText firebaseVisionText) {
// Task completed successfully
mainText.setText("Hello!");
}
})
.addOnFailureListener(
new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// Task failed with an exception
}
}
);
} catch (IOException e) {
e.printStackTrace();
}
FirebaseVisionTextRecognizer detector = FirebaseVision.getInstance().getOnDeviceTextRecognizer();
Note that a catch statement that just prints the runtime exception like yours does, should usually be as high as possible in the callstack. So I'd recommend moving it to the code that alls this code, or even higher up. And keep in mind: if you don't catch that error at all, Android will print it too. So consider what you're trying to accomplish with this catch and implement it accordingly.

Can't fetch expanded URL from a given shortened URL

I am given a shortened url and I want to get the expanded form. The below java function is used to achieve this.
public String expand(String shortenedUrl){
URL url = null;
try {
url = new URL(shortenedUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
// open connection
HttpURLConnection httpURLConnection = null;
try {
httpURLConnection = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
} catch (IOException e) {
e.printStackTrace();
}
// stop following browser redirect
httpURLConnection.setInstanceFollowRedirects(false);
// extract location header containing the actual destination URL
String expandedURL = httpURLConnection.getHeaderField("Location");
httpURLConnection.disconnect();
return expandedURL;
}
The code works fine in Eclipse but the same doesn't work in android.
String expandedURL = httpURLConnection.getHeaderField("Location");
The above line throws java.lang.RuntimeException: Unable to start activity ComponentInfo. And the error is pointed to the above line. If I remove the above line no error is encountered. Even I am not able to use getResponseCode() function.
int status = 0;
try {
status = httpURLConnection.getResponseCode();
} catch (IOException e) {
e.printStackTrace();
}
This piece of code also has the same problem. works in eclipse but not in android.
Any kind of help will be greatly appreciated.
Edit: The code using above function is,
ExpandUrl expandUrl = new ExpandUrl();
String expandedUrl = expandUrl.expand(shortenedUrl);
Note: The function expand is defined inside the class ExpandUrl.
Well, the code works in Eclipse but not in android. The reason is that you are doing it in Main thread and blocking it. Android wouldn't allow you to do so and throw runtime error.
I have tried to implement your code using AsyncTask in android. It works fine.
Give it a try.
To know more about AsyncTask follow: Android Documentation on AsyncTask
Good Luck!

Android unreported exception IOException error

I am new to android apps development. Recently,Im writing an application which able to show public ip based on Ipify. So far, i already:
Download the required jar file and put inside libs folder
I also compile file within gradle
Then i import required class it to my class
How to use Ipify, according to its website:
import org.ipify.Ipify;
public class HelloIP {
public static void main(String[] args) throws IOException {
System.out.println(Ipify.getPublicIp());
}
}
I write the following method to be invoked from another class:
public static String getPublicIp() throws IOException{
String ip = Ipify.getPublicIp();
return ip;
}
Another Class
//Get wifi
getWifiName wifiInfo = new getWifiName();
String myIP = wifiInfo.getPublicIp();
However, i keep getting:
Error:(52, 43) error: unreported exception IOException; must be caught
or declared to be thrown
I tried to modify the code and use the following try and catch, but still got the same error.
public static String getPublicIp() throws IOException{
String myip = Ipify.getPublicIp();
try{
return myip;
}
catch (IOException e){
System.out.println("General I/O exception: " + e.getMessage());
e.printStackTrace();
}
}
Im not too good in catch and throw exception, and already spent the whole day for this.I dont have idea anymore to fix this error..T.T
public static String getPublicIp() {
try{
return Ipify.getPublicIp();
}catch (IOException e){
System.out.println("General I/O exception: " + e.getMessage());
e.printStackTrace();
}
return null;
}
In case it didn't help, clean project in your IDE. You may have some data cached and it might be a reason.
Your problem is in another class! As you have declared the method getPublicIp() to throw IOException that class is afraid of receiving the Exception and therefor requests catching it.
In Java you have two types of Exceptions. Checked and unchecked. Checked Exceptions must be caught.
In Java Exceptions are used for marking unexpected situations. For example parsing non-numeric String to a number (NumberFormatException) or calling a method on a null reference (NullPointerException). You can catch them in many ways.
Unchecked Exceptions are those which extend RunTimeException. They are used for marking unexpected states usually caused by user's input. They shouldn't cause harm and should be worked out with business logic. You don't have to catch them, but sometimes you should.
On the other hand there are Checked Exceptions which mark dangerous situations. For example the application being unable to open a file. As those situations are found dangerous, you must catch them.
try{
//some code
} catch (NumberFormatException e1) {
e.printStackTrace() //very important - handles the Exception but prints the information!
} catch (NullPointerException e2) {
e.printStackTrace();
}
or using the fact, that they all extend Exception:
try {
//somecode
} catch (Exception e) {
e.printStackTrace;
};
or since Java 7:
try {
//somecode
} catch (NullPointerException | NumberFormatException e) {
e.printStackTrace;
};

errors when using the bluetooth sample code on android developer site

I am working to add Bluetooth capabilities to my app and ultimately the device that I want to use is a headset/earpiece. I have begun assembling the code and I partial functionality with it. When I got to the code for setting up a bluetooth connection by server, I got errors when adding the code. I have tried solving the problems through the hover over the error and autocorrect but every time I fix one problem a different on arises. This leads me to believe that I am missing something that autocorrect doesn't know about. I need some help fixing the errors. Useful suggestions for setting a bluetooth codin for the first time would also be appreciated. Errors are surrounded with ||#| xxx |||. Error 1:cannot be resolved. Error 2:cannot be resolved to a variable. Error 3:undefined for the type AcceptSocket.
import java.io.IOException;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
public class AcceptSocket extends Thread {
private static final String MY_UUID = null;
BluetoothServerSocket mmServerSocket;
public void AcceptThread() {
// Use a temporary object that is later asssigned to mmServerSocket,
// because mmServerSocket is final
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code
tmp = ||1|mBluetoothAdapter|||.listenUsingRfcommWithServiceRecord(||2|NAME|||,
MY_UUID);
} catch (IOException e) {
}
mmServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned
while (true) {
try {
socket = mmServerSocket.accept();
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null) {
// Do work to manage the connection (in a separate thread)
||3|manageConnectedSocket|||(socket);
mmServerSocket.close();
break;
}
}
}
/** Will cancel the listening socket, and cause the thread to finish */
public void cancel() {
try {
mmServerSocket.close();
} catch (IOException e) {
}
}
}
Error 1,2: There is no constant called NAME anywhere in the class.
Error 3: There is no method called manageConnectedSocket() in the class.
You can't just copy and paste something from the developer's page and expect it to work. It leads you in the correct direction and you have to fill in the missing pieces.

Categories

Resources