Error fetching resources from assests folder - java

I have recently started a new project, at the moment I am trying to create a SQLite database from within the main activity and read from a text file located in my assests folder. Here is my code:
package com.example.kingmarkmcc.universe;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class MainActivity extends AppCompatActivity {
private Button simulator;
private Button helper;
private Button settings;
private Button milkyway;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
if (v == simulator) {
Intent intent = new Intent(MainActivity.this, Simulator.class);
startActivity(intent);
} else if (v == helper) {
Intent intent = new Intent(MainActivity.this, HelpOptions.class);
startActivity(intent);
} else if (v == settings) {
Intent intent = new Intent(MainActivity.this, Settings.class);
startActivity(intent);
} else {
Intent intent = new Intent(MainActivity.this, MilkyWay.class);
startActivity(intent);
}
}
};
simulator = (Button) findViewById(R.id.buttonr1b1);
simulator.setOnClickListener(listener);
helper = (Button) findViewById(R.id.buttonr1b2);
helper.setOnClickListener(listener);
settings = (Button) findViewById(R.id.buttonr2b1);
settings.setOnClickListener(listener);
milkyway = (Button) findViewById(R.id.buttonr2b2);
milkyway.setOnClickListener(listener);
}
#Override
protected void onStart()
{
super.onStart();
MainActivity myMain = new MainActivity();
myMain.createDB();
}
#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);
}
private void createDB(){
SQLiteDatabase db= null;
final String dbName = "starDB";
final String tableName = "starTable";
String[] rowRead;
String line;
try {
InputStream input;
input = getAssets().open("refinedData.txt");
InputStreamReader inputReader = new InputStreamReader(input);
BufferedReader bufferReader = new BufferedReader(inputReader);
//Retrieve or create DataBase
db = this.openOrCreateDatabase(dbName, MODE_PRIVATE, null);
//Creating table
db.execSQL("CREATE TABLE IF NOT EXISTS "
+ tableName
+ " (id INTEGER, proper TEXT, dist INTEGER , absmag INTEGER , spect TEXT , ci INTEGER , x INTEGER , y INTEGER , z INTEGER , vx INTEGER , vy INTEGER , vz INTEGER);");
while((line = bufferReader.readLine())!= null) {
rowRead = line.split(",");
// Put data into table
db.execSQL("INSERT INTO "
+ tableName
+ " (id, proper, dist, absmag, spect, ci, x, y, z, vx, vy, vz)"
+ " VALUES (" + rowRead[0] + "," + rowRead[1] + "," + rowRead[2] + "," + rowRead[3] + "," + rowRead[4] + "," + rowRead[5] + "," + rowRead[6] + "," + rowRead[7] + "," + rowRead[8] + "," + rowRead[9] + "," + rowRead[10] + "," + rowRead[11] + ");");
}
bufferReader.close();
Cursor c = db.rawQuery("SELECT * FROM " + tableName, null);
int Column1 = c.getColumnIndex("id");
int Column2 = c.getColumnIndex("x");
c.moveToFirst();
int id = c.getInt(Column1);
int x = c.getInt(Column2);
System.out.println(id);
System.out.println(x);
Toast.makeText(MainActivity.this, "End", Toast.LENGTH_LONG).show();
}
catch(Exception e) {
Log.e("Error", "Error", e);}
finally {
if (db != null)
db.close();
}
}
This is the error that I am receiving:
02-04 17:41:28.973 27362-27362/com.example.kingmarkmcc.universe D/AndroidRuntime: Shutting down VM
02-04 17:41:28.974 27362-27362/com.example.kingmarkmcc.universe E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.kingmarkmcc.universe, PID: 27362
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.kingmarkmcc.universe/com.example.kingmarkmcc.universe.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2362)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2424)
at android.app.ActivityThread.access$900(ActivityThread.java:155)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1323)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:139)
at android.app.ActivityThread.main(ActivityThread.java:5298)
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:950)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:106)
at com.example.kingmarkmcc.universe.MainActivity.createDB(MainActivity.java:114)
at com.example.kingmarkmcc.universe.MainActivity.onStart(MainActivity.java:83)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1236)
at android.app.Activity.performStart(Activity.java:6088)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2424) 
at android.app.ActivityThread.access$900(ActivityThread.java:155) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1323) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:139) 
at android.app.ActivityThread.main(ActivityThread.java:5298) 
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:950) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745) 
02-04 17:41:28.977 27362-27362/com.example.kingmarkmcc.universe D/AppTracker: App Event: crash
I have tried to correct this error but cannot seem to figure out the problem! Any help would be much appreciated

Your immediate problem is this:
MainActivity myMain = new MainActivity();
Never create your own instances of activities this way. For starters, they do not work, as you are seeing. Besides, you are in an instance of MainActivity. You do not need a second one. Just call createDB().
Also, you are performing a lot of disk I/O on the main application thread. Your UI will be frozen for quite some time as a result. Do not do this. Please move significant disk I/O to a background thread.
Note that it would be faster for your user, and simpler for you as a developer, to use SQLiteAssetHelper, to package a prepared database in your app, rather than do a bunch of SQL statements to accomplish the same thing.

Related

error with running the android app after adding the settext to the textview

the java file that it's probably the problem from and it's not realted to xml at all:
package com.example.android.randomnumber;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
EditText from = (findViewById(R.id.editTextFrom));
EditText to = (findViewById(R.id.editTextTo));
TextView output =(findViewById(R.id.textViewOutput));
String wfrom = from.getText().toString();
int numberfrom=Integer.parseInt(wfrom);
String wto = to.getText().toString();
int numberto=Integer.parseInt(wto);
Random randomNumberGenerator =new Random();
int number = randomNumberGenerator.nextInt(numberto-numberfrom)+numberfrom;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
output.setText(number);
}
public void generate(View view){
if (from.getText() == null || "".equals(from.getText().toString())){
Toast.makeText(MainActivity.this, "the -From- value is empty!",
Toast.LENGTH_SHORT).show();
return;
}else if (to.getText() == null || "".equals(to.getText().toString())){
Toast.makeText(MainActivity.this, "the -To- value is empty!",
Toast.LENGTH_SHORT).show();
return;
}else if(numberfrom >= numberto){
Toast.makeText(MainActivity.this, "the -To- value must be greater than the -From- value",
Toast.LENGTH_SHORT).show();
return;
}
Log.d("test", "it's from:"+numberfrom+" to this:"+numberto+"generatednumber"+number);
}
}
the error in Logcat thank you in advance:
02-24 14:16:33.865 23117-23117/com.example.android.randomnumber E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.randomnumber, PID: 23117
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.android.randomnumber/com.example.android.randomnumber.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2989)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3260)
at android.app.ActivityThread.access$1000(ActivityThread.java:218)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1734)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6934)
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:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.support.v7.app.AppCompatDelegateImpl.<init>(AppCompatDelegateImpl.java:249)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:182)
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:520)
at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:191)
at com.example.android.randomnumber.MainActivity.<init>(MainActivity.java:15)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1690)
at android.app.Instrumentation.newActivity(Instrumentation.java:1094)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2979)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3260) 
at android.app.ActivityThread.access$1000(ActivityThread.java:218) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1734) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:145) 
at android.app.ActivityThread.main(ActivityThread.java:6934) 
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:1404) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199) 
i tried to run it through my phone the problem is stil and the problem start toshow when i added the output.setText and thank you again...........................................................................
Your logic code is not correct, please change it to
public class MainActivity extends AppCompatActivity {
EditText from;
EditText to;
TextView output;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
from = (findViewById(R.id.editTextFrom));
to = (findViewById(R.id.editTextTo));
output = (findViewById(R.id.textViewOutput));
}
public void generate(View view) {
// Get values of from and to edit text
String wfrom = from.getText().toString();
String wto = to.getText().toString();
// Validate from value
if (TextUtils.isEmpty(wfrom)) {
Toast.makeText(MainActivity.this, "the -From- value is empty!",
Toast.LENGTH_SHORT).show();
return;
}
// Validate to value
if (TextUtils.isEmpty(wto)) {
Toast.makeText(MainActivity.this, "the -To- value is empty!",
Toast.LENGTH_SHORT).show();
return;
}
int numberfrom = Integer.parseInt(wfrom);
int numberto = Integer.parseInt(wto);
// Check whether from larger or equal than to
if (numberfrom >= numberto) {
Toast.makeText(MainActivity.this, "the -To- value must be greater than the -From- value",
Toast.LENGTH_SHORT).show();
return;
}
// Generate a random number in range [from - to]
Random randomNumberGenerator = new Random();
int number = randomNumberGenerator.nextInt(numberto - numberfrom) + numberfrom;
// Display the random number on output text view
output.setText(number + "");
// Log for debug
Log.d("test", "it's from:" + numberfrom + " to this:" + numberto + "generatednumber" + number);
}
}

App Crashed while passing data using Intent on Pressing Next Button (getStringExtra) [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I want to move all data 5 (EditText) from activity 1 to 2
public class MainActivity extends Activity
private EditText fName_ET;
private EditText lName_ET;
private EditText phoneNum_ET;
private EditText eMail_ET;
private EditText deviceModel_ET;
private EditText nameDevice_ET;
private Button nextPage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
fName_ET = (EditText)findViewById(R.id.fName_ET);
lName_ET = (EditText)findViewById(R.id.lName_ET);
phoneNum_ET = (EditText)findViewById(R.id.phone_ET);
eMail_ET = (EditText)findViewById(R.id.mail_ET);
nameDevice_ET = (EditText)findViewById(R.id.name_device);
deviceModel_ET = (EditText)findViewById(R.id.model_device);
nextPage = (Button)findViewById(R.id.next_btn);
nextPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
String fName = fName_ET.getText().toString().trim();
String lName = lName_ET.getText().toString().trim();
String email = eMail_ET.getText().toString().trim();
String phone = phoneNum_ET.getText().toString().trim();
String nameDevice = nameDevice_ET.getText().toString().trim();
String modelDevice =deviceModel_ET.getText().toString().trim();
intent.putExtra("modelDevice",modelDevice);
intent.putExtra("fName", fName);
intent.putExtra("lName", lName);
intent.putExtra("phone", phone);
intent.putExtra("email", email);
intent.putExtra("nameDevice", nameDevice);
startActivity(intent);
}
});
public class Main2Activity extends Activity
{
package com.example.eranp.cp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class Main2Activity extends Activity {
private EditText pro_device_det;
private Button saveDataBase;
private DatabaseReference databaseCustomer, databaseDevice, databaseProblem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main3);
databaseCustomer = FirebaseDatabase.getInstance().getReference("customers");
databaseDevice = FirebaseDatabase.getInstance().getReference("device");
databaseProblem = FirebaseDatabase.getInstance().getReference("problem");
saveDataBase = (Button) findViewById(R.id.save_btn);
pro_device_det = (EditText) findViewById(R.id.pro_device_det);
Intent intent = getIntent();
final String fName = intent.getStringExtra("fName");
final String lName = intent.getStringExtra("lName");
final String phone = intent.getStringExtra("phone");
final String email = intent.getStringExtra("email");
final String modelDevice = intent.getStringExtra("modelDevice");
final String nameDevice = intent.getStringExtra("nameDevice");
saveDataBase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String proDeviceDet = pro_device_det.getText().toString().trim();
String shortProDeviceDet = string3Words(proDeviceDet);
DateFormat df = new SimpleDateFormat("d MMM yyyy, HH:mm");
String date = df.format(Calendar.getInstance().getTime());
if (!TextUtils.isEmpty(proDeviceDet)) {
String id = databaseCustomer.push().getKey();
Customer customer = new Customer(id, fName, lName, email, phone);
databaseCustomer.child(id).setValue(customer);
Device device = new Device(id, nameDevice, modelDevice);
databaseDevice.child(id).setValue(device);
Problem problem = new Problem(id, date, proDeviceDet, 0, shortProDeviceDet);
// Toast.makeText(this , "Customer added", Toast.LENGTH_LONG).show();
} else {
// Toast.makeText(this, "Please write on an empty cell", Toast.LENGTH_LONG).show();
}
}
});
}
private String string3Words(String s) {
String[] splitted = s.split("\\s+");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < splitted.length; i++) {
sb.append(splitted[i]);
if (i == 3) {
break;
}
}
String newS = sb.toString();
return newS;
}
}
log when I press:
down VM 03-09 14:47:16.903 3476-3476/com.example.eranp.clientpage
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.eranp.clientpage, PID: 3476
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.eranp.clientpage/com.example.eranp.clientpage.Main2Activity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2924)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2985)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1635)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6692)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'void
android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference
at
com.example.eranp.clientpage.Main2Activity.onCreate(Main2Activity.java:50)
at android.app.Activity.performCreate(Activity.java:6912)
at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2877)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2985) 
at android.app.ActivityThread.-wrap14(ActivityThread.java) 
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1635) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6692) 
at java.lang.reflect.Method.invoke(Native Method) 
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
Why when I press the next button the app crashing?
Thank you for helping!
You are trying to set a click listener on a button in Main2Activity. Most likely the button can't be inflated from the second activity's layout because it doesn't exist.
android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference at
com.example.eranp.clientpage.Main2Activity.onCreate(Main2Activity.java:50)
at
As per your error log you are getting error because of this
Attempt to invoke virtual method 'void
android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference at com.example.eranp.clientpage.Main2Activity.onCreate(Main2Activity.java:50)
saveDataBase = (Button) findViewById(R.id.save_btn);
saveDataBase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// code...
}
});
Check weather button id is correct and is in same layout of the activity or not.

Illegal destination address sms manager shared preferences

I am using numbers stored in shared preferences to send text messages but when i run the app it crashes and the logcat says there is an illegal destination address how?
here is my logcat
12-30 21:01:30.758 12239-12239/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.android.beez.help2, PID: 12239
java.lang.IllegalArgumentException: Invalid destinationAddress
at android.telephony.SmsManager.sendTextMessage(SmsManager.java:127)
at com.android.beez.help2.MainActivity.sendSms(MainActivity.java:63)
at com.android.beez.help2.MainActivity$2.onClick(MainActivity.java:41)
at android.view.View.performClick(View.java:4475)
at android.view.View$PerformClick.run(View.java:18790)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5328)
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:828)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:644)
at dalvik.system.NativeStart.main(Native Method)
and here is my
MainActivity.java
package com.android.beez.help2;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.LocationManager;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button button;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonInit();
Button setupMa = (Button) findViewById(R.id.setupMA);
setupMa.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent a = new Intent(MainActivity.this,Setup.class);
startActivity(a);
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loadCredit();
sendSms();
}
});
}
protected void sendSms() {
spInit();
String number1 = sharedPreferences.getString("first", "");
String number2 = sharedPreferences.getString("second", "");
String number3 = sharedPreferences.getString("third", "");
String name = sharedPreferences.getString("name", "");
String text = "Help, this is " + name + ", if you are reading this I am in trouble please help me" +
" Iam located at " + "http://www.google.com/maps/place/"+GPSTracker.latitude+","+GPSTracker.longitude+ " " +
"" +
"" +
"-Sent via the Emergency App";
SmsManager manager = SmsManager.getDefault();
manager.sendTextMessage(number1, null, text, null, null);
manager.sendTextMessage(number2, null, text, null, null);
manager.sendTextMessage(number3, null, text, null, null);
boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getBoolean("isFirstRun", true);
if (isFirstRun) {
Intent launchSetups = new Intent(MainActivity.this, Setup.class);
startActivity(launchSetups);
}
}
protected void loadCredit() {
spInit();
String creditLine = sharedPreferences.getString("dialLoadSp","");
Uri number = Uri.parse("tel:"+creditLine);
Intent callIntent = new Intent(Intent.ACTION_DIAL, number);
startActivity(callIntent);
}
public void buttonInit() {
button = (Button) findViewById(R.id.button_main);
}
public void spInit() {
sharedPreferences = MainActivity.this.getSharedPreferences("com.android.beez.help2",MODE_PRIVATE);
}
}
The numbers the messages are being sent to are from editTexts and are the stored in sharedPreferences. could the problem be from shared preferences or is it and issue of the text manager
I think you should specify the destination address add an if... if(num1!="" || num2!="" || num3...)
manager.sendText...
Oh, I know this one :) Hope I'm not to late.
IllegalArgumentException is thrown if destinationAddress or text are empty.
In your case, you have this String number1 = sharedPreferences.getString("first", ""); which means that your number1 is empty at first run of the app, and therefore you get that exception.
Also you didn't provide full code here, where you said that numbers would be fill from edit text.

Null pointer exception android array

I am making an app that has 2 java classes: MainActivity and SecondActivity. MainActivity initiates the SecondActivity by using an onClick method.
The SecondActivity has 2 arrays stored in the strings.xml file. The SecondActivity class wants to store all the array variables from strings.xml to itself, in order to use it for some methods. I think i am doing it the wrong way, as i tried storing the arrays directly in the SecondActivity and it worked but when i am storing the arrays in strings.xml it gives a NullPointerException.
Here is the SecondActivity code:
package com.android.ict.seneca.androidpocketguide;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class SecondActivity extends Activity {
private final String CLASS_NAME = "SecondActivity";
String [] Vocabularies = getResources().getStringArray(R.array.Vocabularies_array);
String [] meanings = getResources().getStringArray(R.array.meanings_array);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_dropdown_item_1line, Vocabularies);
//ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line, meanings);
AutoCompleteTextView textView =
(AutoCompleteTextView) findViewById(R.id.vocabularies);
textView.setThreshold(2); // minimum number of characters to be typed
textView.setAdapter(adapter); // connect the list of suggestions to the View object
}
public void onStart(){
super.onStart();
Log.d( CLASS_NAME, "onStart invoked!" );
}
public void onPause(){
super.onPause();
Log.d( CLASS_NAME, "onPause invoked!!" );
}
public void onResume(){
super.onResume();
Log.d( CLASS_NAME, "onResume invoked!!" );
}
public void onStop(){
super.onStop();
Log.d( CLASS_NAME, "onStop invoked!!!" );
}
public void onDestroy(){
super.onDestroy();
Log.d( CLASS_NAME, "onDestroy INVOKED!!!" );
}
public void onRestart(){
super.onRestart();
Log.d( CLASS_NAME, "onRestart invoked!!" );
}
// event handler for the button
public void onClick(View view) {
Intent data = new Intent();
EditText usr =
(EditText) findViewById(R.id.vocabularies); // get user input
// set the data part (an URI reference) of an intent
data.setData(Uri.parse(usr.getText().toString()));
String s = data.getData().toString();
int flag = 0;
for(int i=0; i<Vocabularies.length;i++)
{
if(s.equals(Vocabularies[i]))
{
flag = i;
}
}
Toast.makeText(this, "YOU'VE ENTERED: " + s, Toast.LENGTH_LONG ).show();
String m = meanings[flag];
String disp = "Vocabulary: " + s + "\n" + "Meaning: " + m;
TextView textViewObj1 = (TextView) findViewById(R.id.meaning);
textViewObj1.setText(disp);
//finish(); //--- close the activity AND RETURN CONTROL TO THE REQUESTING ACTIVITY
//EditText txt_username = (EditText) findViewById(R.id.txt_username);
} // end onClick
}
Here is the MainActivity code:
package com.android.ict.seneca.androidpocketguide;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private final String CLASS_NAME = "FirstActiviy";
private int request_Code = 1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d( CLASS_NAME, "onCreate invoked!" );
}
public void onStart(){
super.onStart();
Log.d( CLASS_NAME, "onStart invoked!" );
}
public void onPause(){
super.onPause();
Log.d( CLASS_NAME, "onPause invoked!!" );
}
public void onResume(){
super.onResume();
Log.d( CLASS_NAME, "onResume invoked!!" );
}
public void onStop(){
super.onStop();
Log.d( CLASS_NAME, "onStop invoked!!!" );
}
public void onDestroy(){
super.onDestroy();
Log.d( CLASS_NAME, "onDestroy INVOKED!!!" );
}
public void onRestart(){
super.onRestart();
Log.d( CLASS_NAME, "onRestart invoked!!" );
}
// event handler for the button (activity 2)
public void onClick(View view) {
startActivityForResult( new Intent(
"com.android.ict.seneca.androidpocketguide.second"), // declared by an intent filter
request_Code); // (requesting) activity ID
Log.d( CLASS_NAME, "after startActivityForResult" );
//intent.setData(Uri.parse("com.seneca.lab2b.abbas"));
//startActivity(intent);
}
/*
public void onActivityResult( int requestCode, // used to match the REQUESTING activity ID
int resultCode, // result code set by the sender (i.e. the TARGET activity)
Intent data ) // an intent passed by the sender (i.e. the TARGET activity)
{
if (requestCode == request_Code) {
if (resultCode == RESULT_OK) {
//TextToSpeech(data.getData().toString());
Intent intent = getIntent();
String s = data.getData().toString();
TextView textViewObj1 = (TextView) findViewById(R.id.line);
textViewObj1.setText(s);
Toast.makeText(
this,
"MESSAGE RECEIVED: " + s, // retrieve data from the intent
// API Question: What is the return type of getData()?
Toast.LENGTH_LONG ).show();
}
}
Log.d( CLASS_NAME, "onActivityResult: what is next?" );
}
// event handler for a button (activity 3)
public void onClick3(View view) {
Intent dataIntent = new Intent( this, ThirdActivity.class );//"com.seneca.lab2b.third"); // explicit intent
// the putExtra( ) method
dataIntent.putExtra( "greeting", "Good morning Android!" );
dataIntent.putExtra( "number", 123 );
// create a Bundle object
Bundle bundle = new Bundle();
bundle.putString( "My name", "Abbas Zoeb" );
bundle.putInt( "Student ID", 56789 );
// putExtras( ): store the bundle in the intent
dataIntent.putExtras( bundle );
// launch the third activity
startActivity( dataIntent );
//startActivity( new Intent( this, ThirdActivity.class ) );
}
*/
}
Here is the error log:
09-21 23:43:19.907 26183-26183/com.android.ict.seneca.androidpocketguide E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.android.ict.seneca.androidpocketguide, PID: 26183
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.android.ict.seneca.androidpocketguide/com.android.ict.seneca.androidpocketguide.SecondActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
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 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:87)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:81)
at com.android.ict.seneca.androidpocketguide.SecondActivity.(SecondActivity.java:22)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317)
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) 
Here is the string.xml file:
<resources>
<string name="app_name">Android Pocket Guide</string>
<string-array name="Vocabularies_array">
<item>activity</item>
<item>AVD</item>
<item>ART</item>
<item>Dalvik</item>
<item>intent</item>
<item>intent filter</item>
<item>explicit intent</item>
<item>implicit intent</item>
<item>LogCat</item>
<item>bundle</item>
<item>Gradle</item>
<item>Android Device Monitor</item>
<item>SDK manager</item>
<item>minSdkVersion</item>
</string-array>
<string-array name="meanings_array">
<item>An activity represents a single screen with a user interface just like window or frame of Java</item>
<item>An Android Virtual Device (AVD) is an emulator configuration that lets you model an actual device by defining hardware and software options to be emulated by the Android Emulator.</item>
<item>Android Runtime (ART) is an application runtime environment used by the Android operating system.</item>
<item>Dalvik is a part of the software stack that makes up the Android platform.</item>
<item>Intent can be defined as a simple message objects which is used to communicate from 1 activity to another.</item>
<item>Specifies the types of intents that an activity, service, or broadcast receiver can respond to</item>
<item>An explicit intent is one that you use to launch a specific app component, such as a particular activity or service in your app</item>
<item>Implicit intents do not name a specific component, but instead declare a general action to perform, which allows a component from another app to handle it.</item>
<item>Logcat is a command-line tool that dumps a log of system messages, including stack traces when the device throws an error and messages that you have written from your app with the Log class.</item>
<item>A Bundle is a set of key/value pairs, where it implements an interface called Parcelable.</item>
<item>Gradle is a custom build tool used to build android packages (apk files) by managing dependencies and providing custom build logic.</item>
<item>Android Device Monitor is a standalone tool that provides a UI for several Android application debugging and analysis tools.</item>
<item>A software development kit that enables developers to create applications for the Android platform.</item>
<item>An integer designating the minimum API Level required for the application to run.</item>
</string-array>
</resources>
Try this way
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Vocabularies = getResources().getStringArray(R.array.Vocabularies_array);
meanings = getResources().getStringArray(R.array.meanings_array);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_dropdown_item_1line, Vocabularies);
//ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line, meanings);
AutoCompleteTextView textView =
(AutoCompleteTextView) findViewById(R.id.vocabularies);
textView.setThreshold(2); // minimum number of characters to be typed
textView.setAdapter(adapter); // connect the list of suggestions to the View object
}
Try declaring your arrays in the global context, then assigning them some value during one of the activity's lifecycle stages (i.e. onCreate(), onResume(), etc.).
The issue you're having is with getResources(). I would create a global variable of type Context. Then, what I would do in onCreate() is this:
context = this;
vocabularies = context.getResources().getStringArray(R.array.Vocabularies_array);
meanings = context.getResources().getStringArray(R.array.meanings_array);
Hope that helps!
These variable initializations...
String [] Vocabularies = getResources().getStringArray(R.array.Vocabularies_array);
String [] meanings = getResources().getStringArray(R.array.meanings_array);
...probably need to go in a constructor, or even more likely in onCreate(...), specifically after
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Initialization of the variables in some method like oncreate/onPostcreated e.g.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Vocabularies = getResources().getStringArray(R.array.Vocabularies_array);
meanings = getResources().getStringArray(R.array.meanings_array);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_dropdown_item_1line, Vocabularies);
//ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line, meanings);
AutoCompleteTextView textView =
(AutoCompleteTextView) findViewById(R.id.vocabularies);
textView.setThreshold(2); // minimum number of characters to be typed
textView.setAdapter(adapter); // connect the list of suggestions to the View object
}

Making android application using pubnub to send GPS information but app crashes and shows no errors

I am making an application that sends realtime messages through a pubnub server to users that are subscribed to the same channel. I have it working so that I can send strings from device to device, but now I want to send GPS information. The user will input a string "GPS" and that will trigger a method to then send the location info instead of that string. I am having trouble with this part because no errors are shown, but the app crashes when I try to open it. I tried debugging, but I can figure out whats going wrong. The debugger takes me out of my activity and into these other java class files that are embedded in java after I get step over the oncreate method. Any help or feedback would be really appreciated, thanks!
Some errors I found in the logcat:
ADB:
ddms: null
java.nio.BufferOverflowException
at java.nio.HeapByteBuffer.put(HeapByteBuffer.java:182)
at com.android.ddmlib.JdwpPacket.movePacket(JdwpPacket.java:235)
at com.android.ddmlib.Debugger.sendAndConsume(Debugger.java:347)
at com.android.ddmlib.Client.forwardPacketToDebugger(Client.java:698)
at com.android.ddmlib.MonitorThread.processClientActivity(MonitorThread.java:344)
at com.android.ddmlib.MonitorThread.run(MonitorThread.java:263)
Device LogCat:
03-20 15:44:56.780 15612-15612/com.example.kunalpatel.pubsub E/SELinux﹕ Function: selinux_android_load_priority [0], There is no sepolicy file
03-20 15:44:56.780 15612-15612/com.example.kunalpatel.pubsub E/SELinux﹕ Function: selinux_android_load_priority [1], There is no sepolicy version file
03-20 15:44:56.780 15612-15612/com.example.kunalpatel.pubsub E/SELinux﹕ Function: selinux_android_load_priority , loading version is VE=SEPF_SAMSUNG-SGH-I257_4.2.2_0025
03-20 15:44:56.780 15612-15612/com.example.kunalpatel.pubsub E/SELinux﹕ selinux_android_seapp_context_reload: seapp_contexts file is loaded from /seapp_contexts
java.lang.RuntimeException: Unable to resume activity {com.example.kunalpatel.pubsub/com.example.kunalpatel.pubsub.MainActivity}: java.lang.ClassCastException: com.example.kunalpatel.pubsub.MainActivity cannot be cast to android.location.LocationListener
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2835)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2864)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2309)
at android.app.ActivityThread.access$700(ActivityThread.java:152)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1284)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5299)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: com.example.kunalpatel.pubsub.MainActivity cannot be cast to android.location.LocationListener
at com.example.kunalpatel.pubsub.MainActivity.onResume(MainActivity.java:221)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1202)
at android.app.Activity.performResume(Activity.java:5404)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2825)
            at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2864)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2309)
            at android.app.ActivityThread.access$700(ActivityThread.java:152)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1284)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:176)
            at android.app.ActivityThread.main(ActivityThread.java:5299)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
            at dalvik.system.NativeStart.main(Native Method)
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.pubnub.api.Callback;
import com.pubnub.api.Pubnub;
import com.pubnub.api.PubnubError;
import com.pubnub.api.PubnubException;
public class MainActivity extends ActionBarActivity {
//Button to subscribe to user specified pubnub channel
private Button channelSubscribeButton;
private EditText subscribeChannelEditText;
private TextView messageLogTextView;
//Button to send message to other devices subscribed on same channel
private Button sendMessageButton;
private EditText sendMessageEditText;
private LocationManager locationManager;
private String provider;
private double lat;
private double lon;
private double accuracy;
private MainActivity activity;
//-------------------------Access PubNub API-------------------------//
//pubnub publish and subscribe keys
Pubnub pubnub = new Pubnub("pub-c-", "sub-c");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Subscribing and sending messages
channelSubscribeButton = (Button) findViewById(R.id.subscribe_button);
subscribeChannelEditText = (EditText) findViewById(R.id.channel_name);
messageLogTextView = (TextView) findViewById(R.id.message_log_text_view);
sendMessageButton = (Button) findViewById(R.id.send_message_button);
sendMessageEditText = (EditText) findViewById(R.id.message_edit_text);
activity = this;
//Get location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//Define criteria for how to select the location provider --> use default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
//Prints GPS provider if there is or isn't one
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
//messageLogTextView.append("GPS Information Not Available");
}
}
#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);
}
public void onChannelButtonClick(View view) {
//Get the user inputted text in
String subscribeChannel = String.valueOf(subscribeChannelEditText.getText());
String yourSubscribeChannel = "Subscribed to the " + subscribeChannel + " Channel";
Toast.makeText(this, yourSubscribeChannel, Toast.LENGTH_SHORT).show();
try {
pubnub.subscribe(subscribeChannel, new Callback() {
#Override
public void connectCallback(String channel, Object message) {
Log.d("PUBNUB", "SUBSCRIBE : CONNECT on channel:" + channel
+ " : " + message.getClass() + " : "
+ message.toString());
}
#Override
public void disconnectCallback(String channel, Object message) {
Log.d("PUBNUB", "SUBSCRIBE : DISCONNECT on channel:" + channel
+ " : " + message.getClass() + " : "
+ message.toString());
}
public void reconnectCallback(String channel, Object message) {
Log.d("PUBNUB", "SUBSCRIBE : RECONNECT on channel:" + channel
+ " : " + message.getClass() + " : "
+ message.toString());
}
//Updates textview with message
#Override
public void successCallback(String channel, Object message) {
Log.d("PUBNUB", "SUBSCRIBE : " + channel + " : "
+ message.getClass() + " : " + message.toString());
updateTextView(message.toString() + "\n");
}
#Override
public void errorCallback(String channel, PubnubError error) {
Log.d("PUBNUB", "SUBSCRIBE : ERROR on channel " + channel
+ " : " + error.toString());
}
}
);
} catch (PubnubException e) {
Log.d("PUBNUB", e.toString());
}
}
public void updateTextView(final String message) {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
try{
messageLogTextView.append(message);
} catch(Exception ex) {
Log.d("pubnub", ex.getMessage());
}
messageLogTextView.setMovementMethod(new ScrollingMovementMethod());
}
});
}
public void onSendMessageButtonClick(View view, Location location) {
String messageToSend = String.valueOf(sendMessageEditText.getText());
Callback callback = new Callback() {
public void successCallback(String channel, Object response) {
}
public void errorCallback(String channel, PubnubError error) {
Log.d("PUBNUB", error.toString());
}
};
String subscribeChannel = String.valueOf(subscribeChannelEditText.getText());
pubnub.publish(subscribeChannel, messageToSend, callback);
//if the user input string is equal to "GPS" then initialize the onLocationChanged method
//if not, print to the string to the log textview
if(messageToSend.equals("GPS")) {
//Print to the textview log the onLocationChanged
onLocationChanged(location);
} else {
updateTextView("GPS cannot be retrieved");
}
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, (LocationListener) this);
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates((LocationListener) this);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
//TODO Auto-generated method stub
}
//method to retrieve location information
public void onLocationChanged(Location location) {
double lat = (double) (location.getLatitude());
double lng = (double) (location.getLongitude());
float accuracy = (float) (location.getAccuracy());
double alt = (double) (location.getAltitude());
double speed = (double) (location.getSpeed());
double heading = (double) (location.getBearing());
messageLogTextView.append(String.valueOf(lat));
messageLogTextView.append(String.valueOf(lng));
messageLogTextView.append(String.valueOf(accuracy));
messageLogTextView.append(String.valueOf(alt));
messageLogTextView.append(String.valueOf(speed ));
messageLogTextView.append(String.valueOf(heading ));
}
}
Your error is this (in the middle of the stack trace you provided):
Caused by: java.lang.ClassCastException: com.example.kunalpatel.pubsub.MainActivity cannot be cast to android.location.LocationListener
at com.example.kunalpatel.pubsub.MainActivity.onResume(MainActivity.java:221)
Examining MainActivity.onResume, it turns out that you're casting your MainActivity to LocationListener. You'll need to implement LocationListener if you want to be able to pass MainActivity to locationManager.requestLocationUpdates.
To do this, first check the documentation for LocationListener. There are four abstract methods, you've implemented two of them so far - onStatusChanged, and onLocationChanged. You need to implement onProviderEnabled, and onProviderDisabled. Then, change your class declaration to:
public class MainActivity extends ActionBarActivity implements LocationListener

Categories