I am working with an android database oriented program. This activity is from one of my tab. When i press that particular tab it will get the value from the db and if any null values from the db it will catch it and show an alertbox and changing to another tab. This is my logic. But it is not executing the catch block. It is going straight to the webview and showing there a null value. Please anyone help me to fix this error.Here is my class...
LocationActivity
import java.util.List;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ProgressBar;
#SuppressLint("SetJavaScriptEnabled")
public class LocationActivity extends Activity {
MainTabActivity mainTab;
WebView mWebView;
GPSTracker g;
double my_lat, my_lon;
String lat, lon, to_lat, to_lon, addressText, temp_lat, temp_lon;
DatabaseHandler db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db = new DatabaseHandler(this);
g = new GPSTracker(this);
Log.d("Reading: ", "Location Activity Reading all Values");
List<Datas> datas = db.getAllDatas();
for (Datas dat : datas) {
try{
to_lat = dat.getlat();
to_lon = dat.getlon();
}catch(NullPointerException e){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Oops!");
// set dialog message
alert
.setMessage("Please select a destination before finding your route!")
.setCancelable(false)
.setPositiveButton("ok",new DialogInterface.OnClickListener() {
#SuppressWarnings("deprecation")
public void onClick(DialogInterface dialog,int id) {
((MainTabActivity)getParent()).getTabHost().setCurrentTab(0);
}
});
// create alert dialog
AlertDialog alertDialog = alert.create();
// show it
alertDialog.show();
Log.d(to_lat, to_lon);
System.out.println("Frim thap thee "+ to_lat + " " + to_lon);
}
}
setContentView(R.layout.webview);
getWindow().setFeatureInt(Window.FEATURE_PROGRESS,Window.PROGRESS_VISIBILITY_ON);
final ProgressBar pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.VISIBLE);
my_lat = g.getLatitude();
my_lon = g.getLongitude();
lat = String.valueOf(my_lat);
lon = String.valueOf(my_lon);
mWebView = (WebView)findViewById(R.id.webview1);
mWebView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
pb.setProgress(progress);
if (progress == 100) {
pb.setVisibility(View.GONE);
}
}
});
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.setWebViewClient(new HelloWebViewClient());
addressText = lat + "," + lon + "+to:" + to_lat + ","+ to_lon;
addressText = addressText.replaceAll(" ", "%20");
addressText = addressText.replaceAll("#", "%23");
mWebView.loadUrl("http://maps.google.com/maps?q=from:"+ addressText);
}
}
getlat and getlon may be null, and therefore not throw an exception. You should replace your try/catch with a if statement which checks for null.
Furthermore the real problem of you NullPointerException is:
Log.d(to_lat, to_lon);
Log.d should be used with the TAG as first param, and the String as second:
Log.d("LOCATION", "From " + to_lat + ", to " + to_lon);
If to_lat and to_lon are null:
log.d(null, null);
will definately cause a crash.
Setting strings to null is by itself not an issue and will not throw a NullPointerException.
However if you would try to call a method on String that is null you would get an Exception.
String s = null; //no problem
s.isEmpty(); //Would throw a nullpointer exception
Remove the try catch clause and do a simple check with if statements
to_lat = dat.getlat();
to_lon = dat.getlon();
if(to_lat == null || to_long == null()
{
//Show the alert
}
first check if you are getting anything in the datas using
if(datas.size()>0)
and then use the for loop.
to_lat, to_lon are Strings and they can be null. So why do you expect to have NPE in the catch block?
Related
I want to use youtubeExtractor for android app and I found library like
compile 'com.github.HaarigerHarald:android-youtubeExtractor:master-SNAPSHOT'
There is a sample code in github I copied it. After I open app, it closes at the same time. There isn't an error in phone and also Logcat. Only there is
W/System: ClassLoader referenced unknown path: /data/app/oz.videos-1/lib/arm64 on logcat. I am not sure this is a error or not. Any suggestion? Thanks in advance.
import android.app.Activity;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.SparseArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
import at.huber.youtubeExtractor.VideoMeta;
import at.huber.youtubeExtractor.YouTubeExtractor;
import at.huber.youtubeExtractor.YtFile;
public class MainActivity extends Activity
{
private static String youtubeLink;
private LinearLayout mainLayout;
private ProgressBar mainProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainLayout = (LinearLayout) findViewById(R.id.main_layout);
mainProgressBar = (ProgressBar) findViewById(R.id.prgrBar);
// Check how it was started and if we can get the youtube link
if (savedInstanceState == null && Intent.ACTION_SEND.equals(getIntent().getAction())
&& getIntent().getType() != null && "text/plain".equals(getIntent().getType()))
{
String ytLink = getIntent().getStringExtra(Intent.EXTRA_TEXT);
if (ytLink != null
&& (ytLink.contains("://youtu.be/") || ytLink.contains("youtube.com/watch?v=")))
{
youtubeLink = ytLink;
// We have a valid link
getYoutubeDownloadUrl(youtubeLink);
}
else
{
Toast.makeText(this, R.string.error_no_yt_link, Toast.LENGTH_LONG).show();
finish();
}
} else if (savedInstanceState != null && youtubeLink != null) {
getYoutubeDownloadUrl(youtubeLink);
} else {
finish();
}
}
private void getYoutubeDownloadUrl(String youtubeLink)
{
new YouTubeExtractor(this)
{
#Override
public void onExtractionComplete(SparseArray<YtFile> ytFiles, VideoMeta vMeta) {
mainProgressBar.setVisibility(View.GONE);
if (ytFiles == null) {
// Something went wrong we got no urls. Always check this.
finish();
return;
}
// Iterate over itags
for (int i = 0, itag; i < ytFiles.size(); i++) {
itag = ytFiles.keyAt(i);
// ytFile represents one file with its url and meta data
YtFile ytFile = ytFiles.get(itag);
// Just add videos in a decent format => height -1 = audio
if (ytFile.getFormat().getHeight() == -1 || ytFile.getFormat().getHeight() >= 360) {
addButtonToMainLayout(vMeta.getTitle(), ytFile);
}
}
}
}.extract(youtubeLink, true, false);
}
private void addButtonToMainLayout(final String videoTitle, final YtFile ytfile)
{
// Display some buttons and let the user choose the format
String btnText = (ytfile.getFormat().getHeight() == -1) ? "Audio " +
ytfile.getFormat().getAudioBitrate() + " kbit/s" :
ytfile.getFormat().getHeight() + "p";
btnText += (ytfile.getFormat().isDashContainer()) ? " dash" : "";
Button btn = new Button(this);
btn.setText(btnText);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String filename;
if (videoTitle.length() > 55) {
filename = videoTitle.substring(0, 55) + "." + ytfile.getFormat().getExt();
} else {
filename = videoTitle + "." + ytfile.getFormat().getExt();
}
filename = filename.replaceAll("\\\\|>|<|\"|\\||\\*|\\?|%|:|#|/", "");
downloadFromUrl(ytfile.getUrl(), videoTitle, filename);
finish();
}
});
mainLayout.addView(btn);
}
private void downloadFromUrl(String youtubeDlUrl, String downloadTitle, String fileName)
{
Uri uri = Uri.parse(youtubeDlUrl);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setTitle(downloadTitle);
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
}
Please try to implement the version 2.0.0 of the library:
implementation 'com.github.HaarigerHarald:android-youtubeExtractor:v2.0.0'
May be your savedInstanceState == null, and then finish() method called.
Try call getYoutubeDownloadUrl() with youtube link after mainProgressBar = (ProgressBar) findViewById(R.id.prgrBar);
I'm having a bit of trouble with a simple app I'm making.
I'll include the code:
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import java.net.URL;
public class login extends AppCompatActivity {
EditText user;
EditText pass;
boolean result_back;
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Button log = (Button) findViewById(R.id.btLogIn2);
log.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
login(v);
}
});
}
public void login(View v)
{
HttpClient client = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpResponse response = null;
user = (EditText) findViewById(R.id.eTUser);
String usuario = user.toString();
pass = (EditText) findViewById(R.id.eTPass);
String passw = pass.toString();
String parametros = "?usuario=" + usuario + "&password=" + passw;
HttpGet httpGet = new HttpGet("http://gie.byethost.com/acces.php" + parametros);
Toast toast2 = Toast.makeText(getApplicationContext(), "Enviando datos", Toast.LENGTH_SHORT);
toast2.show();
try
{
response = client.execute(httpGet, localContext);
toast2 = Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_SHORT);
toast2.show();
}
catch (Exception e)
{
}
// response.toString();
if (response.toString().equalsIgnoreCase("1"))
{
Toast toast1 = Toast.makeText(getApplicationContext(), "Login correcto", Toast.LENGTH_SHORT);
toast1.show();
} else
if (response.toString().equalsIgnoreCase("0"))
{
Toast toast1 = Toast.makeText(getApplicationContext(), "Error de login", Toast.LENGTH_SHORT);
toast1.show();
}
}
}
There's only one button here and neither toast is showing, so I don't see where the app is crashing. Also, I'm a bit new in Android programming, so this may have an obvious solution.
Any comments will be appreciated!
You're doing a network transaction on the main thread. Never do that (or any blocking behavior) on the main thread. Your app might be crashing with an error in logcat related to "StrictMode".
Instead, you need to put all your blocking work on another thread. Android has very specific patterns about how to do that. It's not like you would expect in a normal java app.
You might want to consider doing a search for "android asynchronous programming" and learn about things like AsyncTask, Loader, and Service. There are a lot of great tutorials out there on how to use them. Please don't use Thread directly, as that will only cause you pain.
I'm new in android environment and started a Software development project, so my knowledge is too few in it. I need help in detail.
Problem details:
Project is on ANDROID OCR code source from github Robert m.theis
currently it's outcome is - while i take an image of any written text,it retrieves quite exact output using tesseract engine as text and search in internet.
my work is -
use the text string (digits ) and call to a phone operator.
my project name is automated mobile card recharging system.
so that i took result text from a method getText() class named OcrResult.java and put into my own activity. But i don't know why this don't working in real device.
it builds, run in emulator, but in real device at least it should show messages! But it doesn't.
i also added in manifest.xml file as (angel braces are remover here)
under activity
activity android:name="edu.sfsu.cs.orange.ocr.call.CallManager"
under application
uses-permission android:name="android.permission.CALL_PHONE"
here my code is
package edu.sfsu.cs.orange.ocr.call;
import edu.sfsu.cs.orange.ocr.OcrResult;
import edu.sfsu.cs.orange.ocr.CaptureActivity;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
public class CallManager extends Activity
{
public static final String preString = "*111*";
public static final String postString = "#";
//to store retrieved digits
String finalString;
//to get text result from ocr result
OcrResult getStringResult = new OcrResult();
String middleString = getStringResult.getText();
//if it fails to scan desired digit,call the process again
CaptureActivity tryProcessAgain = new CaptureActivity();
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
public void setString(String x)
{
middleString = x;
}
public String getString( String toBeInserted)
{
if(toBeInserted.length() == 16)
{
int counter = 0;
char [] insertHere = new char[16];
for(int verifier = 0; verifier < 16; verifier ++)
{
insertHere[verifier] = toBeInserted.charAt(verifier);
if(!Character.isDigit(insertHere[verifier]))
{
break;
}
counter ++;
}
if(counter == 16)
{
finalString = preString + toBeInserted + postString;
return finalString;
}
else
{
// #SuppressWarnings("unused")
//Toast toast = Toast.makeText(this, " number scan invalid.....OCR failed. Please try again.", Toast.LENGTH_SHORT);
//toast.show();
return middleString;
}
}
else
{
//#SuppressWarnings("unused")
//Toast toast = Toast.makeText(this, " number scannin invalid...OCR failed. Please try again.", Toast.LENGTH_SHORT);
//toast.show();
return middleString;
}
}
public void CallToOperator(String callMe)
{
Toast toast = Toast.makeText(this,finalString,Toast.LENGTH_SHORT);
toast.show();
//Toast toast1 = Toast.makeText(this,middleString,Toast.LENGTH_SHORT);
//toast1.show();
if(callMe == finalString)
{
try
{
startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + finalString)));
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
tryProcessAgain.onShutterButtonPressContinuous();
}
}
}
I know this kind of question exist but I'm confused in this case. I'm using the following code:
package com.example.GetALocation2;
import com.example.GetALocation2.MyLocation.LocationResult;
import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class GetALocation2 extends Activity {
public static final String LOG_TAG = "------------------GetALocation2";
Double latitude;
TextView tv;
MyLocation myLocation = new MyLocation();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) this.findViewById(R.id.thetext);
tv.setText("Yo there!");
Log.e(LOG_TAG, "Toast will be shown");
Toast.makeText(getBaseContext(), "This is the start!", Toast.LENGTH_SHORT).show();
Log.e(LOG_TAG, "Toast was shown");
locationClick();
}
private void locationClick() {
Log.e(LOG_TAG, "Triggered location click");
myLocation.getLocation(this, locationResult);
}
public void yoThereNull(){
Toast.makeText(getBaseContext(), "Location is unknown.", Toast.LENGTH_SHORT).show();
}
public void yoThereNotNull(){
Toast.makeText( getBaseContext(), "I got the location! Yeah! >>> " + GetALocation2.this.latitude, Toast.LENGTH_SHORT).show();
}
public LocationResult locationResult = new LocationResult(){
#Override
public void gotLocation(final Location location){
//Got the location!
Log.d(LOG_TAG, "Entered gotLocation()");
try{
if( location == null ){
Log.d( LOG_TAG, "Null Location is returned" );
yoThereNull();
}else{
Log.d( LOG_TAG, "A location is found/returned" );
GetALocation2.this.latitude = location.getLatitude();
yoThereNotNull();
}
}catch (NullPointerException e) {
Log.e(LOG_TAG, e.toString());
}catch(Exception e){
Log.e(LOG_TAG, e.toString());
}
};
};
}
when location returns null and call yoThereNull() method, the logcat says: cant create handler inside thread that has not called looper.prepare
but when location returns a value, all is okay. the toast appear.
Anyone knows how to handle this in my case? I'm kinda new to java and android, many thanks for any help! :)
Can you replace
yoThereNotNull();
with
GetALocation2.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
yoThereNotNull();
}
});
You have a problem in this line:
Toast.makeText( getBaseContext(), "I got the location! Yeah! >>> " + GetALocation2.this.latitude, Toast.LENGTH_SHORT).show();
Try using the activity.
Toast.makeText( this, "I got the location! Yeah! >>> " + GetALocation2.this.latitude, Toast.LENGTH_SHORT).show();
This error comes when you create a thread manually inside another thread and so on.. This is one condition that Android can't handle.. Thats why they have given something called AsyncTask, which you can use for doin things in Background.. when this ecxeption arrises u cannot always say that you have error in your code.. sometimes your code is clean but still Android OS will throw this Exception.. So make sure to use AsyncTask instead of creating a Thread by yourself..
i'm creating a login application
the login script is ok it's returned true and false
if the response returns true or 1, i want to make it to go to another activity called inputBarcode, the eclipse showing an error on my Intent line and i don't know what to do
i didn't know the other variations of making Intents
this is my full code, the Intent that i want to call is on the bottom after if(res.equals("1")){ :
package com.nigmagrid.go;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
//import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
public class login extends Activity {
String lokasiTugas;
boolean status_npp;
boolean status_password;
boolean status_lokasi;
Button button;
EditText usernameEditText, passwordEditText;
TextView error;
Spinner lokasiSpinner;
final int minNPP = 3;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.login);
final Button button = (Button) findViewById(R.id.login_button);
final EditText usernameEditText = (EditText) findViewById(R.id.login_npp);
final EditText passwordEditText = (EditText) findViewById(R.id.login_password);
final Spinner lokasiSpinner = (Spinner) findViewById(R.id.spinner1);
final TextView error = (TextView) findViewById(R.id.login_status);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.lokasi_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
lokasiSpinner.setAdapter(adapter);
lokasiSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView adapter, View v, int i, long lng) {
//Toast.makeText(getApplicationContext(), adapter.getItemAtPosition(i).toString(), Toast.LENGTH_SHORT).show();
lokasiTugas = adapter.getItemAtPosition(i).toString();
}
#Override
public void onNothingSelected(AdapterView arg0) {
//do something else
}
});
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
error.setText("Menghubungkan ke server...");
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", usernameEditText.getText().toString()));
postParameters.add(new BasicNameValuePair("password", passwordEditText.getText().toString()));
String response = null;
String sNPP = usernameEditText.getText().toString().replace(" ", "");
String sPassword = passwordEditText.getText().toString();
// validasi NPP
if(sNPP.length()<=minNPP){
usernameEditText.setError("NPP minimal "+minNPP+" angka");
status_npp = false;
}else{
status_npp = true;
//Toast.makeText(getApplicationContext(), "NPP Anda : "+sNPP, Toast.LENGTH_SHORT).show();
}
// validasi Password
if(sPassword.length()<1){
passwordEditText.setError("Kata sandi diperlukan");
status_password = false;
}else{
status_password = true;
}
//validasi lokasiTugas
if(lokasiTugas.equals("Pilih Lokasi")){
Toast.makeText(getApplicationContext(), "Lokasi Tugas diperlukan", Toast.LENGTH_SHORT).show();
status_lokasi = false;
}else{
status_lokasi = true;
}
// pengecekan akhir
if(status_npp == true && status_password == true && status_lokasi == true){
//Toast.makeText(getApplicationContext(), "NPP Anda : "+sNPP+"\nLokasi : "+lokasiTugas, Toast.LENGTH_SHORT).show();
//fungsi login disini :D
try{
// variabel cek-nya ganti
String cek = "http://almezuflash.zxq.net/kspt-android/ceklogin.php";
response = CustomHttpClient.excecuteHttpPost(cek, postParameters);
String res = response.toString();
res = res.replaceAll("\\s", "");
Toast.makeText(getApplicationContext(), res, Toast.LENGTH_SHORT).show();
if(res.equals("1")){
error.setText("Login sukses");
Toast.makeText(getApplicationContext(), "Login Sukses", Toast.LENGTH_SHORT).show();
// i want to make Intent but eclipse says error, and i don't know what to do
Intent doBarcode = new Intent(parent, inputBarcode.class);
startActivity(doBarcode);
}else{
error.setText("Login gagal");
//Toast.makeText(getApplicationContext(), "Login Gagal", Toast.LENGTH_SHORT).show();
}
}catch (Exception e){
//error.setText(e.toString());
error.setText("Terjadi kesalahan, silahkan periksa koneksi internet anda");
}
}else{
//Toast.makeText(getApplicationContext(), "Otorisasi Gagal", Toast.LENGTH_SHORT).show();
status_npp = false;
status_password = false;
status_lokasi = false;
error.setText("Login gagal, silahkan periksa kembali");
}
}
});
}
}
Sorry for my bad english, i'm from Indonesia fyi :D
Did you make sure to add the inputBarCode activity to your AndroidManifiest? If you did not, then that will give a runtime error. If thats no the problem, then possibly changing
Intent doBarcode = new Intent(parent, inputBarcode.class);
to
Intent doBarcode = new Intent(this, inputBarcode.class);
will solve your problem. I'm not familiar with the parent variable being used.
I hope that helps.
Try instead of
Intent doBarcode = new Intent(parent, inputBarcode.class);
use this code:
Intent doBarcode = new Intent(login.this, inputBarcode.class);