Can't run my MQTT application on Android Studio - java

i'm testing a personal MQTT application but it failed when i click on the connect button... There is an exception but i don't know where it comes from.
Here is my code
MainActivity.java :
package com.application.phoste.homecontrol;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private Paho paho = null;
EditText topic = null;
EditText message = null;
Button connect = null;
Button send = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
paho = new Paho();
topic = (EditText) findViewById(R.id.topic);
message = (EditText) findViewById(R.id.message);
connect = (Button) findViewById(R.id.connect);
connect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
paho.connect();
String res = (paho.isConnected()) ? "Connected" : "Not Connected";
Toast toast = Toast.makeText(getApplicationContext(), res, Toast.LENGTH_SHORT);
toast.show();
}
});
send = (Button) findViewById(R.id.send);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
paho.publish(topic.getText().toString(), message.getText().toString());
Toast toast = Toast.makeText(getApplicationContext(), "Message sent", Toast.LENGTH_SHORT);
toast.show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Paho.java :
package com.application.phoste.homecontrol;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
public class Paho implements MqttCallback {
private MqttClient client;
private static final String BROKER = "tcp://192.168.1.189:1883";
private static final int QOS = 2;
public void connect() {
try {
client = new MqttClient(BROKER, MqttClient.generateClientId());
MqttConnectOptions options = new MqttConnectOptions();
options.setConnectionTimeout(1);
client.setCallback(this);
client.connect();
} catch (MqttException e) {
e.getMessage();
}
}
public void disconnect() {
if (client.isConnected()) {
try {
client.disconnect();
} catch (MqttException e) {
e.getMessage();
}
}
}
public boolean isConnected() {
return client.isConnected();
}
public void publish(String topic, String m) {
try {
MqttMessage message = new MqttMessage(m.getBytes());
message.setQos(2);
client.publish(topic, message);
} catch (MqttException e) {
e.getMessage();
}
}
#Override
public void connectionLost(Throwable throwable) {
}
#Override
public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
}
#Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
}
}
The exception :
07-29 15:17:23.988 15718-15718/com.application.phoste.homecontrol E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.application.phoste.homecontrol, PID: 15718
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean org.eclipse.paho.client.mqttv3.MqttClient.isConnected()' on a null object reference
at com.application.phoste.homecontrol.Paho.isConnected(Paho.java:44)
at com.application.phoste.homecontrol.MainActivity$1.onClick(MainActivity.java:35)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19748)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
I also added the <uses-permission android:name="android.permission.internet"/> line into the AndroidManifest.xml
Where am I wrong ?
Edit :
I just realized i had some warning messages even before the exception was thrown... Here they are :
07-29 17:26:52.673 32706-32706/com.application.phoste.homecontrol W/System.err﹕ MqttException (0)
07-29 17:26:52.673 32706-32706/com.application.phoste.homecontrol W/System.err﹕ at org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence.open(MqttDefaultFilePersistence.java:80)
07-29 17:26:52.673 32706-32706/com.application.phoste.homecontrol W/System.err﹕ at org.eclipse.paho.client.mqttv3.MqttAsyncClient.<init>(MqttAsyncClient.java:286)
07-29 17:26:52.674 32706-32706/com.application.phoste.homecontrol W/System.err﹕ at org.eclipse.paho.client.mqttv3.MqttAsyncClient.<init>(MqttAsyncClient.java:167)
07-29 17:26:52.674 32706-32706/com.application.phoste.homecontrol W/System.err﹕ at org.eclipse.paho.client.mqttv3.MqttClient.<init>(MqttClient.java:224)
07-29 17:26:52.674 32706-32706/com.application.phoste.homecontrol W/System.err﹕ at org.eclipse.paho.client.mqttv3.MqttClient.<init>(MqttClient.java:136)
07-29 17:26:52.675 32706-32706/com.application.phoste.homecontrol W/System.err﹕ at com.application.phoste.homecontrol.MainActivity.onCreate(MainActivity.java:35)
07-29 17:26:52.675 32706-32706/com.application.phoste.homecontrol W/System.err﹕ at android.app.Activity.performCreate(Activity.java:5933)
07-29 17:26:52.676 32706-32706/com.application.phoste.homecontrol W/System.err﹕ at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
07-29 17:26:52.676 32706-32706/com.application.phoste.homecontrol W/System.err﹕ at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2282)
07-29 17:26:52.676 32706-32706/com.application.phoste.homecontrol W/System.err﹕ at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2389)
07-29 17:26:52.676 32706-32706/com.application.phoste.homecontrol W/System.err﹕ at android.app.ActivityThread.access$900(ActivityThread.java:147)
07-29 17:26:52.676 32706-32706/com.application.phoste.homecontrol W/System.err﹕ at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1296)
07-29 17:26:52.676 32706-32706/com.application.phoste.homecontrol W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:102)
07-29 17:26:52.676 32706-32706/com.application.phoste.homecontrol W/System.err﹕ at android.os.Looper.loop(Looper.java:135)
07-29 17:26:52.676 32706-32706/com.application.phoste.homecontrol W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5254)
07-29 17:26:52.676 32706-32706/com.application.phoste.homecontrol W/System.err﹕ at java.lang.reflect.Method.invoke(Native Method)
07-29 17:26:52.676 32706-32706/com.application.phoste.homecontrol W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:372)
07-29 17:26:52.676 32706-32706/com.application.phoste.homecontrol W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
07-29 17:26:52.678 32706-32706/com.application.phoste.homecontrol W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
I really hope someone could help me with that.
I also changed my code to do everything in the MainActivity :
package com.application.phoste.homecontrol;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
public class MainActivity extends Activity {
EditText topic = null;
EditText message = null;
Button send = null;
Button debug = null;
MqttClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
client = new MqttClient("tcp://m2m.eclipse.org:1883", MqttClient.generateClientId());
MqttConnectOptions options = new MqttConnectOptions();
options.setConnectionTimeout(1);
client.connect();
} catch (MqttException e) {
e.printStackTrace();
}
topic = (EditText) findViewById(R.id.topic);
message = (EditText) findViewById(R.id.message);
send = (Button) findViewById(R.id.send);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
MqttMessage m = new MqttMessage(message.getText().toString().getBytes());
m.setQos(2);
client.publish(topic.getText().toString(), m);
Toast toast = Toast.makeText(getApplicationContext(), "Message sent", Toast.LENGTH_SHORT);
toast.show();
} catch (MqttException e) {
e.printStackTrace();
}
}
});
debug = (Button) findViewById(R.id.debug);
debug.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String res = (client == null) ? "Null" : "Not Null";
Toast toast = Toast.makeText(getApplicationContext(), res, Toast.LENGTH_SHORT);
toast.show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
But it still doesn't work, I get the Null Toast from de debug button.

OK, so you need to set up the MQTT file persistence path and this will require write access to the SD card and the path you give it.
https://www.eclipse.org/paho/files/javadoc/index.html?org/eclipse/paho/client/mqttv3/persist/MqttDefaultFilePersistence.html
You will also need to add the right permission to access the file system.

Your "client" object is not initialized when you are trying to take some action on it.
Move this line: client = new MqttClient(BROKER, MqttClient.generateClientId());
to somewhere else in your application (maybe onCreate() ) to ensure the variable is properly initialized before you access it.i

Related

ImageButton to open a new activity

I am building an android app and on the main layout i have 3 Image Buttons which when clicked they must each open a new activity.
When I run the app and pressed on them the app crushes. this is the code i am using:
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton converterbtn = (ImageButton)findViewById(R.id.btnConvert);
ImageButton placesbtn = (ImageButton)findViewById(R.id.imagBtnPlace);
ImageButton weatherbtn = (ImageButton)findViewById(R.id.imgbtnweather);
//Open Weather Activity
if (weatherbtn.isPressed() == true) {
weatherbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), weather_mainActivity.class);
startActivity(intent);
}
}); //Open Currency Activity
}else if (converterbtn.isPressed() == true) {
converterbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent1 = new Intent(getApplicationContext(), CurrencyConverter_MainActivity.class);
startActivity(intent1);
}
});//Open Places Activity
} else if (placesbtn.isPressed()) {
placesbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent1 = new Intent(getApplicationContext(), Places_mainActivity.class);
startActivity(intent1);
}
});
}
}
Manifest.xml
<activity android:name=".CurrencyConverter_MainActivity"/>
<activity android:name=".weather_mainActivity"/>
Any ideas why that happens? All the other posts ive checked are doing it with this way but on mine it doesnt seem to work.
Android Monitor log
01-08 03:00:58.288 22447-22447/? D/AndroidRuntime: Shutting down VM
--------- beginning of crash
01-08 03:01:01.127 1236-1547/? D/AudioFlinger: mixer(0xf4480000) throttle end: throttle time(56)
01-08 03:01:01.151 1550-21914/? D/OpenGLRenderer: endAllStagingAnimators on 0x7f0b1b83d400 (RippleDrawable) with handle 0x7f0b1b8bb540
01-08 03:01:01.192 1550-1954/? D/GraphicsStats: Buffer count: 3
Weather_MainActivity.java
package com.android.example.cwapp;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import butterknife.ButterKnife;
import butterknife.InjectView;
public class weather_mainActivity extends AppCompatActivity {
public static final String TAG = weather_mainActivity.class.getSimpleName();
private CurrentWeather mCurrentWeather;
LocationManager locationManager;
#InjectView(R.id.timeLabel) TextView mTimeLabel;
#InjectView(R.id.temperatureLabel)TextView mTemperatureLabel;
#InjectView(R.id.humidityValue)TextView mHumidityValue;
#InjectView(R.id.precipValue)TextView mPrecipValue;
#InjectView(R.id.summaryLabel)TextView mSummaryLabel;
#InjectView(R.id.iconImageView)ImageView mIconImageView;
#InjectView(R.id.refreshImageView)ImageView mRefreshImageView;
#InjectView(R.id.progressBar)ProgressBar mProgressBar;
#InjectView(R.id.locationLabel)TextView mLocation;
public double latitude /*= 34.7720*/;
public double longitude /*= 32.4297*/;
//Location Manager
private boolean checkLocation() {
if (!isLocationEnabled())
showAlert();
return isLocationEnabled();
}
private void showAlert() {
final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Enable Location")
.setMessage("Your Locations Settings is set to 'Off'.\nPlease Enable Location to " +
"use this app")
.setPositiveButton("Location Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
}
});
dialog.show();
}
private boolean isLocationEnabled() {
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
private final LocationListener locationListenerBest = new LocationListener() {
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
mProgressBar.setVisibility(View.INVISIBLE);
mRefreshImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getForecast(latitude, longitude);
}
});
getForecast(latitude, longitude);
Log.d(TAG, "Main UI code is running!");
}
private void getForecast(double latitude, double longitude) {
String apiKey = "6180f6e1b6747c1da3cb4638ea9d2961";
String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
"/" + latitude + "," + longitude;
if (isNetworkAvailable()) {
toggleRefresh();
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(forecastUrl)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
alertUserAboutError();
}
#Override
public void onResponse(Response response) throws IOException {
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
try {
String jsonData = response.body().string();
Log.v(TAG, jsonData);
if (response.isSuccessful()) {
mCurrentWeather = getCurrentDetails(jsonData);
runOnUiThread(new Runnable() {
#Override
public void run() {
updateDisplay();
}
});
} else {
alertUserAboutError();
}
} catch (IOException e) {
Log.e(TAG, "Exception caught: ", e);
} catch (JSONException e) {
Log.e(TAG, "Exception caught: ", e);
}
}
});
} else {
Toast.makeText(this, getString(R.string.network_unavailable_message),
Toast.LENGTH_LONG).show();
}
}
private void toggleRefresh() {
if (mProgressBar.getVisibility() == View.INVISIBLE) {
mProgressBar.setVisibility(View.VISIBLE);
mRefreshImageView.setVisibility(View.INVISIBLE);
} else {
mProgressBar.setVisibility(View.INVISIBLE);
mRefreshImageView.setVisibility(View.VISIBLE);
}
}
private void updateDisplay() {
float temp = mCurrentWeather.getTemperature();
String temp2 = Float.toString((temp - 32) * (5 / 9));
mTemperatureLabel.setText(temp2 + "");
mTimeLabel.setText("At " + mCurrentWeather.getFormattedTime() + " it will be");
mHumidityValue.setText(mCurrentWeather.getHumidity() + "");
mPrecipValue.setText(mCurrentWeather.getPrecipChance() + "%");
mSummaryLabel.setText(mCurrentWeather.getSummary());
mLocation.setText(mCurrentWeather.getTimeZone());
Drawable drawable = getResources().getDrawable(mCurrentWeather.getIconId());
mIconImageView.setImageDrawable(drawable);
}
private CurrentWeather getCurrentDetails(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
Log.i(TAG, "From JSON: " + timezone);
JSONObject currently = forecast.getJSONObject("currently");
CurrentWeather currentWeather = new CurrentWeather();
currentWeather.setHumidity(currently.getDouble("humidity"));
currentWeather.setTime(currently.getLong("time"));
currentWeather.setIcon(currently.getString("icon"));
currentWeather.setPrecipChance(currently.getDouble("precipProbability"));
currentWeather.setSummary(currently.getString("summary"));
currentWeather.setTemperature(currently.getDouble("temperature"));
currentWeather.setTimeZone(timezone);
Log.d(TAG, currentWeather.getFormattedTime());
return currentWeather;
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private void alertUserAboutError() {
AlertDialogFragment_weather dialog = new AlertDialogFragment_weather();
dialog.show(getFragmentManager(), "error_dialog");
}
};
RUN Log
01-09 21:29:30.827 5610-5610/? E/memtrack: Couldn't load memtrack module (No such file or directory)
01-09 21:29:30.827 5610-5610/? E/android.os.Debug: failed to load memtrack module: -2
01-09 21:29:30.864 5610-5627/? E/art: Thread attaching while runtime is shutting down: Binder_2
01-09 21:29:30.869 5614-5614/? E/memtrack: Couldn't load memtrack module (No such file or directory)
01-09 21:29:30.870 5614-5614/? E/android.os.Debug: failed to load memtrack module: -2
01-09 21:29:30.916 1548-1596/? E/InputDispatcher: channel '6ba3a14 com.android.example.cwapp/com.android.example.cwapp.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
01-09 21:29:31.830 5633-5633/? E/memtrack: Couldn't load memtrack module (No such file or directory)
01-09 21:29:31.830 5633-5633/? E/android.os.Debug: failed to load memtrack module: -2
01-09 21:29:32.033 1195-1309/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property
01-09 21:29:33.170 1921-2145/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0xedc344f0
01-09 21:30:01.551 5641-5654/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b819a240
01-09 21:30:02.902 5641-5654/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b1cf8310
01-09 21:30:04.739 5641-5654/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b819b580
01-09 21:30:06.655 5641-5654/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b1cf8380
01-09 21:30:08.253 5641-5654/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b1bed700
01-09 21:30:09.115 5641-5641/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.android.example.cwapp, PID: 5641
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android.example.cwapp/com.android.example.cwapp.Places_mainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at com.android.example.cwapp.Places_mainActivity.onCreate(Places_mainActivity.java:36)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
01-09 21:30:11.307 1548-1601/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b1c8f020
01-09 21:30:11.326 1548-1937/? E/JavaBinder: !!! FAILED BINDER TRANSACTION !!! (parcel size = 104)
Add CurrentWeather.class activity in your mainfest like this
<activity android:name=".CurrencyConverter_MainActivity"/>
<activity android:name=".weather_mainActivity"/>
<activity android:name=".CurrentWeather"/>
You should display your stack trace, but you don't need View.OnClickListner, not sure if that's causing it, but just have weatherbtn.setOnClickListener(new OnClickListener() {...
Other than that, there isn't anything wrong with how you're calling your activity.

error in android application ArrayList

Hello how are you? I'm creating an android app news and is working very well, the only problem is when I'm doing the reading of the text and minimize the app to do something else and then return the app presents this error.
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: FATAL EXCEPTION: main
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: at java.util.ArrayList.get(ArrayList.java:304)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: at com.brfgd.ActivityDetailStory.setAdapterToListview(ActivityDetailStory.java:179)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: at com.brfgd.ActivityDetailStory$MyTask.onPostExecute(ActivityDetailStory.java:171)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: at com.brfgd.ActivityDetailStory$MyTask.onPostExecute(ActivityDetailStory.java:119)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: at android.os.AsyncTask.finish(AsyncTask.java:631)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: at android.os.AsyncTask.access$600(AsyncTask.java:177)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:99)
03-21 16:49:03.279 10567-10567/? E/AndroidRuntime: at android.os.Looper.loop(Looper.java:153)
part of the error
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class ActivityDetailStory extends AppCompatActivity {
int position;
String str_cid, str_cat_id, str_cat_image, str_cat_name, str_title, str_image, str_desc, str_date;
TextView news_title, news_date;
WebView news_desc;
ImageView img_news, img_fav;
DatabaseHandler db;
List<ItemStoryList> arrayOfRingcatItem;
ItemStoryList objAllBean;
final Context context = this;
ProgressBar progressBar;
LinearLayout content;
private AdView mAdView;
private InterstitialAd interstitial;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_story);
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final android.support.v7.app.ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(Constant.CATEGORY_TITLE);
}
//show admob banner ad
mAdView = (AdView) findViewById(R.id.adView);
mAdView.loadAd(new AdRequest.Builder().build());
mAdView.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
}
#Override
public void onAdFailedToLoad(int error) {
mAdView.setVisibility(View.GONE);
}
#Override
public void onAdLeftApplication() {
}
#Override
public void onAdOpened() {
}
#Override
public void onAdLoaded() {
mAdView.setVisibility(View.VISIBLE);
}
});
content = (LinearLayout) findViewById(R.id.content);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
img_fav = (FloatingActionButton) findViewById(R.id.img_fav);
img_news = (ImageView) findViewById(R.id.image);
news_title = (TextView) findViewById(R.id.title);
news_date = (TextView) findViewById(R.id.subtitle);
news_desc = (WebView) findViewById(R.id.desc);
db = new DatabaseHandler(ActivityDetailStory.this);
arrayOfRingcatItem = new ArrayList<ItemStoryList>();
//imageLoader = new ImageLoader(ActivityDetailStory.this);
if (JsonUtils.isNetworkAvailable(ActivityDetailStory.this)) {
new MyTask().execute(Constant.SERVER_URL + "/api.php?nid=" + Constant.NEWS_ITEMID);
MyApplication.getInstance().trackScreenView("Lendo de cara : " + (Constant.CATEGORY_TITLE));
}
else {
Toast.makeText(getApplicationContext(), "Problema com sua Rede de Internet", Toast.LENGTH_SHORT).show();
}
}
private class MyTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... params) {
return JsonUtils.getJSONString(params[0]);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressBar.setVisibility(View.GONE);
content.setVisibility(View.VISIBLE);
if (null == result || result.length() == 0) {
Toast.makeText(getApplicationContext(), "Problema com sua Rede de Internet!", Toast.LENGTH_SHORT).show();
} else {
try {
JSONObject mainJson = new JSONObject(result);
JSONArray jsonArray = mainJson.getJSONArray(Constant.CATEGORY_ARRAY_NAME);
JSONObject objJson = null;
for (int i = 0; i < jsonArray.length(); i++) {
objJson = jsonArray.getJSONObject(i);
ItemStoryList objItem = new ItemStoryList();
objItem.setCId(objJson.getString(Constant.CATEGORY_ITEM_CID));
objItem.setCategoryName(objJson.getString(Constant.CATEGORY_ITEM_NAME));
objItem.setCategoryImage(objJson.getString(Constant.CATEGORY_ITEM_IMAGE));
objItem.setCatId(objJson.getString(Constant.CATEGORY_ITEM_CAT_ID));
objItem.setNewsImage(objJson.getString(Constant.CATEGORY_ITEM_NEWSIMAGE));
objItem.setNewsHeading(objJson.getString(Constant.CATEGORY_ITEM_NEWSHEADING));
objItem.setNewsDescription(objJson.getString(Constant.CATEGORY_ITEM_NEWSDESCRI));
objItem.setNewsDate(objJson.getString(Constant.CATEGORY_ITEM_NEWSDATE));
arrayOfRingcatItem.add(objItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
setAdapterToListview();
}
}
}
public void setAdapterToListview() {
//if(arrayOfRingcatItem.size()>0) {
objAllBean = arrayOfRingcatItem.get(0);
str_cid = objAllBean.getCId();
str_cat_name = objAllBean.getCategoryName();
str_cat_image = objAllBean.getCategoryImage();
str_cat_id = objAllBean.getCatId();
str_title = objAllBean.getNewsHeading();
str_desc = objAllBean.getNewsDescription();
str_image = objAllBean.getNewsImage();
str_date = objAllBean.getNewsDate();
news_title.setText(str_title);
news_date.setText(str_date);
news_desc.setBackgroundColor(Color.parseColor("#FFFFFF"));
news_desc.setFocusableInTouchMode(false);
news_desc.setFocusable(false);
news_desc.getSettings().setDefaultTextEncodingName("UTF-8");
WebSettings webSettings = news_desc.getSettings();
Resources res = getResources();
int fontSize = res.getInteger(R.integer.font_size);
webSettings.setDefaultFontSize(fontSize);
String mimeType = "text/html; charset=UTF-8";
String encoding = "utf-8";
String htmlText = str_desc;
String text = "<html><head><style type=\"text/css\">#font-face {font-family: MyFont;src: url(\"file:///android_asset/Roboto-Light.ttf\")}body {font-family: MyFont;font-size: medium; color: #525252;}</style></head><body>"
+ htmlText + "</body></html>";
news_desc.loadData(text, mimeType, encoding);
List<Pojo> pojolist = db.getFavRow(str_cat_id);
if (pojolist.size() == 0) {
img_fav.setImageResource(R.drawable.ic_bookmark_outline);
} else {
if (pojolist.get(0).getCatId().equals(str_cat_id))
;
{
img_fav.setImageResource(R.drawable.ic_bookmark_white);
}
}
img_fav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
List<Pojo> pojolist = db.getFavRow(str_cat_id);
if (pojolist.size() == 0) {
db.AddtoFavorite(new Pojo(str_cat_id, str_cid, str_cat_name, str_title, str_image, str_desc, str_date));
Toast.makeText(getApplicationContext(), "Leitura Marcada", Toast.LENGTH_SHORT).show();
img_fav.setImageResource(R.drawable.ic_bookmark_white);
interstitial = new InterstitialAd(ActivityDetailStory.this);
interstitial.setAdUnitId(getString(R.string.admob_interstitial_id));
AdRequest adRequest = new AdRequest.Builder().build();
interstitial.loadAd(adRequest);
interstitial.setAdListener(new AdListener() {
public void onAdLoaded() {
if (interstitial.isLoaded()) {
interstitial.show();
}
}
});
} else {
if (pojolist.get(0).getCatId().equals(str_cat_id)) {
db.RemoveFav(new Pojo(str_cat_id));
Toast.makeText(getApplicationContext(), "Leitura desmarcada!", Toast.LENGTH_SHORT).show();
img_fav.setImageResource(R.drawable.ic_bookmark_outline);
}
}
}
});
//}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_story, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
onBackPressed();
break;
case R.id.menu_share:
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Estou lendo vários livro com esse app estou adorando, baixe já, Recomendo "+"https://play.google.com/store/apps/details?id="+getPackageName());
sendIntent.setType("text/plain");
startActivity(sendIntent);
break;
default:
return super.onOptionsItemSelected(menuItem);
}
return true;
}
#Override
protected void onPause() {
// mAdView.pause();
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
//mAdView.resume();
}
#Override
protected void onDestroy() {
//mAdView.destroy();
super.onDestroy();
}
}
You should do this:
public void setAdapterToListview() {
if(arrayOfRingcatItem.size>0){
objAllBean = arrayOfRingcatItem.get(0);
str_cid = objAllBean.getCId();
str_cat_name = objAllBean.getCategoryName();
}
}
EDIT: onResume()
#Override
protected void onResume(){
super.onResume();
arrayOfRingcatItem = new ArrayList<ItemStoryList>();
//imageLoader = new ImageLoader(ActivityDetailStory.this);
if (JsonUtils.isNetworkAvailable(ActivityDetailStory.this)) {
new MyTask().execute(Constant.SERVER_URL + "/api.php?nid=" + Constant.NEWS_ITEMID);
MyApplication.getInstance().trackScreenView("Lendo de cara : " + (Constant.CATEGORY_TITLE));
}
else {
Toast.makeText(getApplicationContext(), "Problema com sua Rede de Internet", Toast.LENGTH_SHORT).show();
}
}
Or you can save the array in the Application class and use it from there, or in a singleton. The error it's because when the activity go to background Android can release some memory and delete your array.
EDIT 2: You can use SharedPreferences to save the id.
You have to put this code in onCreate:
SharedPreferences opc=getSharedPreferences("AppName", 0);
SharedPreferences.Editor editor =opc.edit();
editor.putInt("ID_SAVED",NEWS_ITEMID); editor.commit();
And in the onResume:
SharedPreferences opc=getSharedPreferences("AppName", 0);
NEWS_ITEMID=opc.getInt("ID_SAVED", -1);
Based on what you stated above everything is working fine except:
minimize the app to do something else and then return the app presents this error
You may need to reinitialize code in:
#Override
public void onResume(){
super.onResume();
// put your code here to repopulate arraylist...
refreshMyData();
}
refreshMyData could have:
public void refreshMyData(){
if (JsonUtils.isNetworkAvailable(ActivityDetailStory.this)) {
new MyTask().execute(Constant.SERVER_URL + "/api.php?nid=" + Constant.NEWS_ITEMID);
MyApplication.getInstance().trackScreenView("Lendo de cara : " + (Constant.CATEGORY_TITLE));
}else {
Toast.makeText(getApplicationContext(), "Problema com sua Rede de Internet", Toast.LENGTH_SHORT).show();
}
}
Use this method in your oncreate as well, that way you can have the same method call when creating the activity and resuming.
Sources:
How to use onResume()?

Android, gps. App with GPS's localizzation

I've ha problem: I 'm implementing a secondary Activity that give to me user's position. From Page1.java, through a button, open Track.java when I would like to show the coordinates of the user's location. The problem is when I click on this button: the application is closed!
This is the code of Page1.java:
package com.example.giacomob.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by Giacomo B on 05/08/2015.
*/
public class Page1 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page1);
// String dato1 = getIntent().getExtras().getString("NomeDati1");
//Intent intent = getIntent(); // Point 1
// Bundle bundle = intent.getExtras(); // Point 2
// String data1 = bundle.getString("NomeDati1"); // Point 3
String dato1 = getIntent().getExtras().getString("NomeDati1"); //preleva la stringa
Toast.makeText(this, dato1, Toast.LENGTH_SHORT).show(); //PROVA: questo mi fa comparire una specie di label notifica trasparente con il valore di "data1"
Log.d("TAG", "data1:" + dato1); //credo sia una specie di debug
// String salve = getIntent().getExtras().getString("ciao");
// System.out.println("questo è il valore della prima variabile" +salve);
//FARE CONTROLLO IN CASO IL FILE XML E' VUOTO E QUINDI LA STRINGA E' VUOTA
String[] arr = dato1.split("\\|");
for (int i = 0; i < arr.length; i++) {
System.out.println(i + " => " + arr[i]);
}
final ArrayList <String> listp = new ArrayList<String>();
for (int i = 0; i < arr.length; ++i) {
listp.add(arr[i]);
}
// recupero la lista dal layout
final ListView mylist = (ListView) findViewById(R.id.listView1);
// creo e istruisco l'adattatore
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listp);
// inietto i dati
mylist.setAdapter(adapter);
Button b_load=(Button)findViewById(R.id.button_send2);
b_load.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent openTrack = new Intent(Page1.this, Track.class);
startActivity(openTrack);
}
});
}
This is the code of Track.java:
package com.example.giacomob.myapplication;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
/**
* Created by Giacomo B on 07/08/2015.
*/
public class Track extends ActionBarActivity implements LocationListener {
/* #Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_track);
}
String providerId = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
private final int MIN_DIST=20;
private static final int MIN_PERIOD=30000; */
private String providerId = LocationManager.GPS_PROVIDER;
private LocationManager locationManager=null;
private static final int MIN_DIST=20;
private static final int MIN_PERIOD=30000;
/*if(!providerId.contains("gps"))
{
final Intent intent = new Intent();
intent.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
intent.setData(Uri.parse("3"));
sendBroadcast(intent);
}*/
#Override
protected void onResume()
{
if (!locationManager.isProviderEnabled(providerId))
{
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
super.onResume();
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(providerId))
{
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
else
locationManager.requestLocationUpdates(providerId, MIN_PERIOD, MIN_DIST, this);
}
private void updateGUI(Location location)
{
double latitude=location.getLatitude();
double longitude=location.getLongitude();
String msg="Ci troviamo in coordinate ("+latitude+","+longitude+")";
TextView txt= (TextView) findViewById(R.id.locationText);
txt.setText(msg);
}
#Override
protected void onPause()
{
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location)
{
updateGUI(location);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle)
{ }
#Override
public void onProviderEnabled(String s)
{ }
#Override
public void onProviderDisabled(String s)
{ }
}
And this is the code of the xml file associate to Track.java, called "activity_track.xml":
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="In attesa di essere localizzati..."
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="25sp"
android:id="#+id/locationText"/>
</RelativeLayout>
This is LogCat's code:
08-08 00:04:23.801 2217-2217/com.example.giacomob.myapplication I/art﹕ Not late-enabling -Xcheck:jni (already on)
08-08 00:04:24.035 2217-2234/com.example.giacomob.myapplication I/OpenGLRenderer﹕ Initialized EGL, version 1.4
08-08 00:04:24.070 2217-2234/com.example.giacomob.myapplication W/EGL_emulation﹕ eglSurfaceAttrib not implemented
08-08 00:04:24.070 2217-2234/com.example.giacomob.myapplication W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xb4398620, error=EGL_SUCCESS
08-08 00:04:25.762 2217-2217/com.example.giacomob.myapplication I/System.out﹕ Root element :destinazione
08-08 00:04:25.762 2217-2217/com.example.giacomob.myapplication I/System.out﹕ ----------------------------
08-08 00:04:25.762 2217-2217/com.example.giacomob.myapplication I/System.out﹕ [ 08-08 00:04:25.762 2217: 2217 I/System.out ]
Current Element :destinazione
08-08 00:04:25.762 2217-2217/com.example.giacomob.myapplication I/System.out﹕ Coordinata X : 1
08-08 00:04:25.762 2217-2217/com.example.giacomob.myapplication I/System.out﹕ 1
08-08 00:04:25.762 2217-2217/com.example.giacomob.myapplication I/System.out﹕ Naziome : Italia
08-08 00:04:25.762 2217-2217/com.example.giacomob.myapplication I/System.out﹕ Paese : Cannole
08-08 00:04:25.762 2217-2217/com.example.giacomob.myapplication I/System.out﹕ Via : Piazza San Vincenzo
08-08 00:04:25.864 2217-2217/com.example.giacomob.myapplication I/System.out﹕ 0 => 1
08-08 00:04:25.864 2217-2217/com.example.giacomob.myapplication I/System.out﹕ 1 => 2
08-08 00:04:25.864 2217-2217/com.example.giacomob.myapplication I/System.out﹕ 2 => Italia
08-08 00:04:25.864 2217-2217/com.example.giacomob.myapplication I/System.out﹕ 3 => Cannole
08-08 00:04:25.864 2217-2217/com.example.giacomob.myapplication I/System.out﹕ 4 => Piazza San Vincenzo
08-08 00:04:25.919 2217-2234/com.example.giacomob.myapplication W/EGL_emulation﹕ eglSurfaceAttrib not implemented
08-08 00:04:25.919 2217-2234/com.example.giacomob.myapplication W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa511b960, error=EGL_SUCCESS
08-08 00:04:26.166 2217-2234/com.example.giacomob.myapplication W/EGL_emulation﹕ eglSurfaceAttrib not implemented
08-08 00:04:26.166 2217-2234/com.example.giacomob.myapplication W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xb4398900, error=EGL_SUCCESS
08-08 00:04:26.893 2217-2217/com.example.giacomob.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.giacomob.myapplication, PID: 2217
java.lang.RuntimeException: Unable to resume activity {com.example.giacomob.myapplication/com.example.giacomob.myapplication.Track}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.location.LocationManager.isProviderEnabled(java.lang.String)' on a null object reference
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2989)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3020)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.location.LocationManager.isProviderEnabled(java.lang.String)' on a null object reference
at com.example.giacomob.myapplication.Track.onResume(Track.java:39)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1257)
at android.app.Activity.performResume(Activity.java:6076)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2978)
            at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3020)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
This is the update of Track.java
package com.example.giacomob.myapplication;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
/**
* Created by Giacomo B on 07/08/2015.
*/
public class Track extends ActionBarActivity implements LocationListener {
/* #Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_track);
}
String providerId = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
private final int MIN_DIST=20;
private static final int MIN_PERIOD=30000; */
private String providerId = LocationManager.GPS_PROVIDER;
// private LocationManager locationManager=null;
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
private static final int MIN_DIST = 20;
private static final int MIN_PERIOD = 30000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page1);
this.locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
#Override
protected void onResume()
{
if (!locationManager.isProviderEnabled(providerId))
{
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
super.onResume();
// LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(providerId))
{
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
else
locationManager.requestLocationUpdates(providerId, MIN_PERIOD, MIN_DIST, this);
}
private void updateGUI(Location location)
{
double latitude=location.getLatitude();
double longitude=location.getLongitude();
String msg="Ci troviamo in coordinate ("+latitude+","+longitude+")";
TextView txt= (TextView) findViewById(R.id.locationText);
txt.setText(msg);
}
#Override
protected void onPause()
{
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location)
{
updateGUI(location);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle)
{ }
#Override
public void onProviderEnabled(String s)
{ }
#Override
public void onProviderDisabled(String s)
{ }
}
I don't understand the reason for witch the app is closed! Please, help me! Thanks
You never instantiate your LocationManager reference. This must be done in onCreate like this:
LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
The app crashes due to a Null Pointer Exception.
The answer of andrewdleach is correct; and the exact line to add in onCreate is this:
this.locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
EDIT:
ok, try to use this
package com.example.giacomob.myapplication;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
/**
* Created by Giacomo B on 07/08/2015.
*/
public class Track extends ActionBarActivity implements LocationListener
{
String providerId = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
private final int MIN_DIST=20;
private static final int MIN_PERIOD=30000; */
private String providerId = LocationManager.GPS_PROVIDER;
private LocationManager locationManager=null;
private static final int MIN_DIST=20;
private static final int MIN_PERIOD=30000;
/*if(!providerId.contains("gps"))
{
final Intent intent = new Intent();
intent.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
intent.setData(Uri.parse("3"));
sendBroadcast(intent);
}*/
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_track);
this.locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
}
#Override
protected void onResume()
{
if (locationManager == null)
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(providerId))
{
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
super.onResume();
if (!locationManager.isProviderEnabled(providerId))
{
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
else
{
locationManager.requestLocationUpdates(providerId, MIN_PERIOD, MIN_DIST, this);
}
}
private void updateGUI(Location location)
{
double latitude=location.getLatitude();
double longitude=location.getLongitude();
String msg="Ci troviamo in coordinate ("+latitude+","+longitude+")";
TextView txt= (TextView) findViewById(R.id.locationText);
txt.setText(msg);
}
#Override
protected void onPause()
{
super.onPause();
if (locationManager != null)
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location)
{
updateGUI(location);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle)
{ }
#Override
public void onProviderEnabled(String s)
{ }
#Override
public void onProviderDisabled(String s)
{ }
}

fatal exception: main java.lang.RuntimeException in android map,

i'm currently working on android maps by following this tutorial http://developer.android.com/training/location/retrieve-current.html, and i keep getting error.there are 4 warnings and i tried to fix it but when i run it again the error message fatal exception still showing
here's the warning messages:
1. the message servicesConnected() from the type LokasiKampus is never used locally
2. the value of local variable kampus is not used
3. the value of local variable laboratorium is not used
4.the value of local variable myCurrentLocation is not used
here's my Java code
package ninth.example.dteinformationcenter;
import android.app.Activity;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class LokasiKampus extends FragmentActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener{
static final LatLng Kampus = new LatLng (-7.775038, 110.373253);
static final LatLng Laboratorium = new LatLng (-7.765437, 110.374496);
private static final int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private GoogleMap map;
private GooglePlayServicesClient myLocationClient;
public static class ErrorDialogFragment extends DialogFragment {
private Dialog mDialog;
public ErrorDialogFragment() {
super();
mDialog = null;
}
public void setDialog(Dialog dialog) {
mDialog = dialog;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return mDialog;
}
public void show(FragmentManager supportFragmentManager, String tag) {
// TODO Auto-generated method stub
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case CONNECTION_FAILURE_RESOLUTION_REQUEST :
switch(resultCode) {
case Activity.RESULT_OK : break;
}
}
}
**private boolean servicesConnected()** {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == resultCode) {
Log.d("Location Updated", "Google Play Services is available");
return true;
} else {
Dialog ErrorDialog = GooglePlayServicesUtil
.getErrorDialog(resultCode, this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
if (ErrorDialog != null) {
ErrorDialogFragment errorFragment = new ErrorDialogFragment();
errorFragment.setDialog(ErrorDialog);
errorFragment.show(getSupportFragmentManager(), "Location Updates");
}
return false;
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lokasi_kampus);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.lokasikampus)).getMap();
if (map != null) {
**Marker kampus = map.addMarker(new MarkerOptions().position(Kampus)
.title("Kampus "));
Marker laboratorium = map.addMarker(new MarkerOptions().position(Laboratorium)
.position(Laboratorium)
.title("Laboratorium")
);**
map.moveCamera(CameraUpdateFactory.newLatLngZoom(Kampus, 18));
map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
}
LocationClient myLocationClient = new LocationClient(this,this,this);
**Location myCurrentLocation;
myCurrentLocation = myLocationClient.getLastLocation();**
}
#Override
public void onConnected(Bundle dataBundle) {
Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
}
#Override
public void onDisconnected() {
Toast.makeText(this, "Disconnected, please re-connect", Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if(connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch(IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
Toast.makeText(this, "Connection Failed", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onStart() {
super.onStart();
myLocationClient.connect();
}
#Override
protected void onStop() {
myLocationClient.disconnect();
super.onStop();
}
}
this is the error message
FATAL EXCEPTION: main
Process: ninth.example.dteinformationcenter, PID: 1443
java.lang.RuntimeException: Unable to start activity ComponentInfo{ninth.example.dteinformationcenter/ninth.example.dteinformationcenter.LokasiKampus}: java.lang.IllegalStateException: Not connected. Call connect() and wait for onConnected() to be called.
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalStateException: Not connected. Call connect() and wait for onConnected() to be called.
at com.google.android.gms.internal.hb.cn(Unknown Source)
at com.google.android.gms.internal.jg.b(Unknown Source)
at com.google.android.gms.internal.jg$c.cn(Unknown Source)
at com.google.android.gms.internal.jf.getLastLocation(Unknown Source)
at com.google.android.gms.internal.jg.getLastLocation(Unknown Source)
at com.google.android.gms.location.LocationClient.getLastLocation(Unknown Source)
at ninth.example.dteinformationcenter.LokasiKampus.onCreate(LokasiKampus.java:112)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)

threadid=1: thread exiting with uncaught exception error

I'm recieving an error of threadid=1... I don't always get it but I do at a point in the app at sometime. Not sure what my specific error is. I've check line 164 and I don't see anything that would cause the result. Maybe something I need to add into my manifest? Here is my LogCat.
05-08 17:19:28.796: W/dalvikvm(8683): threadid=1: thread exiting with uncaught exception (group=0x40e37438)
05-08 17:19:28.806: E/AndroidRuntime(8683): FATAL EXCEPTION: main
05-08 17:19:28.806: E/AndroidRuntime(8683): java.lang.NullPointerException
05-08 17:19:28.806: E/AndroidRuntime(8683): at com.example.speech.MainActivity$SpeechListener.onResults(MainActivity.java:164)
05-08 17:19:28.806: E/AndroidRuntime(8683): at android.speech.SpeechRecognizer$InternalListener$1.handleMessage(SpeechRecognizer.java:442)
05-08 17:19:28.806: E/AndroidRuntime(8683): at android.os.Handler.dispatchMessage(Handler.java:99)
05-08 17:19:28.806: E/AndroidRuntime(8683): at android.os.Looper.loop(Looper.java:137)
05-08 17:19:28.806: E/AndroidRuntime(8683): at android.app.ActivityThread.main(ActivityThread.java:4918)
05-08 17:19:28.806: E/AndroidRuntime(8683): at java.lang.reflect.Method.invokeNative(Native Method)
05-08 17:19:28.806: E/AndroidRuntime(8683): at java.lang.reflect.Method.invoke(Method.java:511)
05-08 17:19:28.806: E/AndroidRuntime(8683): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
05-08 17:19:28.806: E/AndroidRuntime(8683): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
05-08 17:19:28.806: E/AndroidRuntime(8683): at dalvik.system.NativeStart.main(Native Method)
Here is my Main Activity Code:
package com.example.speech;
import java.util.ArrayList;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.app.Activity;
import android.content.Intent;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.view.Menu;
import android.view.View.OnClickListener;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.util.Log;
public class MainActivity extends Activity implements OnClickListener {
private SpeechRecognizer mSpeechRecognizer;
private Intent mSpeechRecognizerIntent;
boolean reseter = false;
private AudioManager mAudioManager;
private volatile boolean mNoSpeechCountDownOn;
MediaPlayer testSound;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
boolean available = SpeechRecognizer.isRecognitionAvailable(this);
Log.d("Speech", "available = " + available);
testSound = MediaPlayer.create(MainActivity.this, R.raw.soundclip);
mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
mSpeechRecognizer.setRecognitionListener(new SpeechListener());
mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
this.getPackageName());
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS, 0);
mAudioManager = (AudioManager) getSystemService(this.AUDIO_SERVICE);
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
mAudioManager.setStreamMute(AudioManager.STREAM_SYSTEM, true);
Log.d("speech", "Mute on");
try {
Thread.sleep(4000);
Log.d("speech", "repeat");
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
mAudioManager.setStreamMute(AudioManager.STREAM_SYSTEM, true);
Log.d("speech", "Mute on");
} catch (InterruptedException e) {
}
}
private CountDownTimer mNoSpeechCountDown = new CountDownTimer(5000, 5000)
{
#Override
public void onTick(long millisUntilFinished)
{
}
#SuppressWarnings("synthetic-access")
#Override
public void onFinish()
{
mNoSpeechCountDownOn = false;
mSpeechRecognizer.cancel();
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class SpeechListener implements RecognitionListener {
#Override
public void onBeginningOfSpeech() {
if (mNoSpeechCountDownOn)
{
mNoSpeechCountDownOn = false;
mNoSpeechCountDown.cancel();
}
Log.d("Speech", "onBeginningOfSpeech");
}
#Override
public void onBufferReceived(byte[] buffer) {
Log.d("Speech", "onBufferReceived");
}
#Override
public void onEndOfSpeech() {
Log.d("Speech", "onEndOfSpeech");
}
#Override
public void onError(int error) {
if (mNoSpeechCountDownOn)
{
mNoSpeechCountDownOn = false;
mNoSpeechCountDown.cancel();
}
Log.d("Speech", "onError");
}
#Override
public void onEvent(int eventType, Bundle params) {
Log.d("Speech", "onEvent");
}
#Override
public void onPartialResults(Bundle partialResults) {
Log.d("Speech", "onPartialResults");
}
#Override
public void onReadyForSpeech(Bundle params) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
{
mNoSpeechCountDownOn = true;
mNoSpeechCountDown.start();
mAudioManager.setStreamMute(AudioManager.STREAM_SYSTEM, false);
}
Log.d("Speech", "onReadyForSpeech");
try {
Thread.sleep(6000);
Log.d("speech", "repeat");
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
mAudioManager.setStreamMute(AudioManager.STREAM_SYSTEM, true);
Log.d("speech", "Mute on");
} catch (InterruptedException e) {
}}
#Override
public void onResults(Bundle results) {
Log.d("Speech", "results");
ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
for (String match : matches) { if (match.equals("one")) testSound.start();
else if (match.equals("two")) testSound.start();
}
// Do whatever you want here
try {
Thread.sleep(1);
Log.d("speech", "repeat");
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
mAudioManager.setStreamMute(AudioManager.STREAM_SYSTEM, true);
Log.d("speech", "Mute on");
} catch (InterruptedException e) {
}
}
#Override
public void onRmsChanged(float rmsdB) {
//Log.d("Speech", "onRmsChanged");
}
}
#Override
public void onClick(View arg0) {
//must keep the onClick
}
}
05-08 17:19:28.806: E/AndroidRuntime(8683): java.lang.NullPointerException
05-08 17:19:28.806: E/AndroidRuntime(8683): at com.example.speech.MainActivity$SpeechListener.onResults(MainActivity.java:164)
Guessing that line 164 is
else if (match.equals("two")) testSound.start();
I suspect your match can be null sometimes. If so, the match.equals... code will crash for pretty much obvious reason. The simplest solution is to change this line, from:
else if (match.equals("two")) testSound.start();
to more safe form:
else if ("two".equals(match)) testSound.start();
ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
if(matches!=null) {
for (String match : matches)
/* ... */
}
matches may be null if there are no matches.

Categories