Cursor people = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (people.moveToNext()){
int NameIndex = people.getColumnIndex(PhoneLookup.DISPLAY_NAME);
int NumIndex = people.getColumnIndex(PhoneLookup.NUMBER);
String Name = people.getString(NameIndex);
//String Num = people.getString(NumIndex);
myArr.add(Name.toString());
myNum.add(Num.toString());
}
Hello I am experiencing problems retrieving a contact's phone number where each time i enable this line of code
String Num = people.getString(NumIndex);
03-03 15:38:30.436: E/AndroidRuntime(496): FATAL EXCEPTION: main
03-03 15:38:30.436: E/AndroidRuntime(496): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.GhattasAk.RingMe/com.GhattasAk.RingMe.Main}: java.lang.IllegalStateException: get field slot from row 0 col -1 failed
03-03 15:38:30.436: E/AndroidRuntime(496): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
03-03 15:38:30.436: E/AndroidRuntime(496): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
03-03 15:38:30.436: E/AndroidRuntime(496): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
03-03 15:38:30.436: E/AndroidRuntime(496): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
03-03 15:38:30.436: E/AndroidRuntime(496): at android.os.Handler.dispatchMessage(Handler.java:99)
03-03 15:38:30.436: E/AndroidRuntime(496): at android.os.Looper.loop(Looper.java:123)
03-03 15:38:30.436: E/AndroidRuntime(496): at android.app.ActivityThread.main(ActivityThread.java:3683)
03-03 15:38:30.436: E/AndroidRuntime(496): at java.lang.reflect.Method.invokeNative(Native Method)
03-03 15:38:30.436: E/AndroidRuntime(496): at java.lang.reflect.Method.invoke(Method.java:507)
03-03 15:38:30.436: E/AndroidRuntime(496): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
03-03 15:38:30.436: E/AndroidRuntime(496): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
03-03 15:38:30.436: E/AndroidRuntime(496): at dalvik.system.NativeStart.main(Native Method)
03-03 15:38:30.436: E/AndroidRuntime(496): Caused by: java.lang.IllegalStateException: get field slot from row 0 col -1 failed
03-03 15:38:30.436: E/AndroidRuntime(496): at android.database.CursorWindow.getString_native(Native Method)
03-03 15:38:30.436: E/AndroidRuntime(496): at android.database.CursorWindow.getString(CursorWindow.java:329)
03-03 15:38:30.436: E/AndroidRuntime(496): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:49)
03-03 15:38:30.436: E/AndroidRuntime(496): at android.database.CursorWrapper.getString(CursorWrapper.java:135)
03-03 15:38:30.436: E/AndroidRuntime(496): at com.GhattasAk.RingMe.Main.onCreate(Main.java:49)
03-03 15:38:30.436: E/AndroidRuntime(496): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
03-03 15:38:30.436: E/AndroidRuntime(496): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
03-03 15:38:30.436: E/AndroidRuntime(496): ... 11 more
the application crashes.. I do not understand why
this is the edit to get a name based on a number is this true ?
if(state==TelephonyManager.CALL_STATE_RINGING)
{
// Find contact based on name.
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
"NUMBER = '" + number + "'", null, null);
if (cursor.moveToFirst()) {
String contactId =
cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
// Get all phone numbers.
Cursor phones = cr.query(Phone.CONTENT_URI, null,
Phone.CONTACT_ID + " = " + contactId, null, null);
while (phones.moveToNext()) {
String numb = phones.getString(phones.getColumnIndex(Phone.DISPLAY_NAME));
}
phones.close();
}
cursor.close();
Probably becouse the contact have multiple phone nrs like work...
try this:
// Find contact based on name.
//
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
"DISPLAY_NAME = '" + NAME + "'", null, null);
if (cursor.moveToFirst()) {
String contactId =
cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
//
// Get all phone numbers.
//
Cursor phones = cr.query(Phone.CONTENT_URI, null,
Phone.CONTACT_ID + " = " + contactId, null, null);
while (phones.moveToNext()) {
String number = phones.getString(phones.getColumnIndex(Phone.NUMBER));
int type = phones.getInt(phones.getColumnIndex(Phone.TYPE));
switch (type) {
case Phone.TYPE_HOME:
// do something with the Home number here...
break;
case Phone.TYPE_MOBILE:
// do something with the Mobile number here...
break;
case Phone.TYPE_WORK:
// do something with the Work number here...
break;
}
}
phones.close();
}
cursor.close();
Related
When i am trying to display the contacts in card view when i click on Button it shows fatal exception error it doesnot display cardview anyone can solve this programming with brillliance and another error is it show only one cardview when i click on again the app will be strucked?
Showcontacts.java
public class ShowContacts extends Activity
{
private SQLiteDatabase db;
DbOperations doo;
private List<Contacts> contactsList;
private RecyclerView rv;
private Cursor c;
String names,email,address;
int phone;
String read_query = "select * from"+ ContactsTask.ContactsEntry.TABLE_NAME;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recycle_layout);
doo = new DbOperations(this);
openDatabase();
rv = (RecyclerView)findViewById(R.id.recyclerview);
initializeData();
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
rv.setLayoutManager(linearLayoutManager);
rv.setHasFixedSize(true);
ContactAdapter cc = new ContactAdapter(contactsList);
rv.setAdapter(cc);
}
public void initializeData() {
contactsList = new ArrayList<>();
c = db.rawQuery(read_query,null);
c.moveToFirst();
while (!c.isLast())
{
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
}
c.isLast();
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
}
private void openDatabase() {
db = openOrCreateDatabase("contactDB", Context.MODE_PRIVATE,null);
}
}
Logacat error
06-28 08:57:43.107 568-568/com.example.anilkumar.contactstask E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.anilkumar.contactstask/com.example.anilkumar.contactstask.ShowContacts}: android.database.sqlite.SQLiteException: near "fromcontacts": syntax error: , while compiling: select * fromcontacts
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
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:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.database.sqlite.SQLiteException: near "fromcontacts": syntax error: , while compiling: select * fromcontacts
at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:68)
at android.database.sqlite.SQLiteProgram.compileSql(SQLiteProgram.java:143)
at android.database.sqlite.SQLiteProgram.compileAndbindAllArgs(SQLiteProgram.java:361)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:127)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:94)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:53)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:47)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1564)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1538)
at com.example.anilkumar.contactstask.ShowContacts.initializeData(ShowContacts.java:44)
at com.example.anilkumar.contactstask.ShowContacts.onCreate(ShowContacts.java:34)
at android.app.Activity.performCreate(Activity.java:4466)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
Another logact error
06-28 13:14:40.552 11252-11261/com.example.anilkumar.contactstask E/SQLiteDatabase: close() was never explicitly called on database '/data/data/com.example.anilkumar.contactstask/databases/contactDB'
android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here
at android.database.sqlite.SQLiteDatabase.<init>(SQLiteDatabase.java:1943)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:1007)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:986)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:962)
at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:1043)
at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:1036)
at android.app.ContextImpl.openOrCreateDatabase(ContextImpl.java:761)
at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:215)
at com.example.anilkumar.contactstask.ShowContacts.openDatabase(ShowContacts.java:66)
at com.example.anilkumar.contactstask.ShowContacts.onCreate(ShowContacts.java:33)
at android.app.Activity.performCreate(Activity.java:4466)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
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:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
Just update
String read_query = "select * from"+ ContactsTask.ContactsEntry.TABLE_NAME;
to
String read_query = "select * from "+ ContactsTask.ContactsEntry.TABLE_NAME;
Always close cursor. update your initializeData method
public void initializeData() {
try {
contactsList = new ArrayList<>();
try{
c = db.rawQuery(read_query,null);
c.moveToFirst();
while (!c.isLast())
{
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
}
c.isLast();
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
} catch (Exception e) {
// exception handling
} finally {
if(c != null){
c.close();
}
}
}
i try to delete the data from listview by using the context menu and i get this java.lang.IllegalStateException: Couldn't read row 0, col 2 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
public List<AssignmentRecord> getAllAssignment(){
List<AssignmentRecord> records = new ArrayList<AssignmentRecord>();
Cursor cursor = database.query(AssigmentContract.Assigment.TABLE_NAME, allColumn , null,
null, null, null, null);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
AssignmentRecord assignmentRecord = new AssignmentRecord();
assignmentRecord.setAssname(cursor.getString(0));
assignmentRecord.setAssTime(cursor.getString(1));
assignmentRecord.setAssID(cursor.getString(2));
records.add(assignmentRecord);
cursor.moveToNext();
}
first line error assignmentRecord.setAssID(cursor.getString(2));
dbcon.open();
List<AssignmentRecord> records = dbcon.getAllAssignment();
dbcon.close();
second error is List records = dbcon.getAllAssignment();
private static final String SQL_CREATE_ENTRIES = "CREATE TABLE "
+ AssigmentContract.Assigment.TABLE_NAME +
"(" + AssigmentContract.Assigment.COLUMN_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " +
AssigmentContract.Assigment.COLUMN_ASS + " TEXT," +
AssigmentContract.Assigment.COLUMN_ASSDATE+ " TEXT)";
public final class AssigmentContract {
public AssigmentContract(){}
public static abstract class Assigment implements BaseColumns{
public static final String TABLE_NAME ="AssignmentV2";
public static final String COLUMN_ASS ="AssignmentTitle";
public static final String COLUMN_ASSDATE ="AssignmentDate";
public static final String COLUMN_ID ="AssignmentID";
}
}
LOGCAT
my.com.chyi.schedulev2 E/CursorWindow﹕ Failed to read row 0, column 2 from a CursorWindow which has 1 rows, 2 columns.
my.com.chyi.schedulev2 D/AndroidRuntime﹕ Shutting down VM
my.com.chyi.schedulev2 W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x9e4f5908)
/my.com.chyi.schedulev2 E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{my.com.chyi.schedulev2/my.com.chyi.schedulev2.assigmentActivity}: java.lang.IllegalStateException: Couldn't read row 0, col 2 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
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:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalStateException: Couldn't read row 0, col 2 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at android.database.CursorWindow.nativeGetString(Native Method)
at android.database.CursorWindow.getString(CursorWindow.java:434)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
at my.com.chyi.schedulev2.SQLController.getAllAssignment(SQLController.java:102)
at my.com.chyi.schedulev2.assigmentActivity.onCreate(assigmentActivity.java:73)
at android.app.Activity.performCreate(Activity.java:5104)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230
at android.app.ActivityThread.access$600(ActivityThread.java:141)at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234 at android.os.Handler.dispatchMessage(Handler.java:99)at android.os.Looper.loop(Looper.java:137)at android.app.ActivityThread.main(ActivityThread.java:5041) 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:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Try this,
while(!cursor.isAfterLast()){
AssignmentRecord assignmentRecord = new AssignmentRecord();
assignmentRecord.setAssname(cursor.getString(cursor.getColumnIndex("your_respective_column_name));
assignmentRecord.setAssTime(cursor.getString(cursor.getColumnIndex("your_respective_column_name)));
assignmentRecord.setAssID(cursor.getString(cursor.getColumnIndex("your_respective_column_name)));
records.add(assignmentRecord);
cursor.moveToNext();
I have demonstrated what Harry suggested you to do. Here replace your_respective column name with the value you given for the columns which your trying to retrieve. For Ex: when you are trying to fetch the value of AssId it will be _id or some thing. Hope this helps you.
Your getAllAssignment() should be as,
List<AssignmentRecord> records = new ArrayList<AssignmentRecord>();
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery("select * from " + TABLE_NAME, null);
if(cursor.moveToFirst()){
do {
AssignmentRecord assignmentRecord = new AssignmentRecord();
assignmentRecord.setAssID(cursor.getString(0));
assignmentRecord.setAssname(cursor.getString(1));
assignmentRecord.setAssTime(cursor.getString(2));
} while(cursor.moveToNext());
}
database.close();
I am trying to display the duration between power connected and disconnected in my app....i am trying to do it like below ...
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.batterystat);
batteryStatInfo = (TextView) findViewById(R.id.batteryStatusInfo);
this.registerReceiver(this.batteryStatRec, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
private BroadcastReceiver batteryStatRec = new BroadcastReceiver()
{
public void onReceive(Context context, Intent intent)
{
int health = intent.getIntExtra(BatteryManager.EXTRA_HEALTH,0);
int icon = intent.getIntExtra(BatteryManager.EXTRA_ICON_SMALL, 0);
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
int chargingBy = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
boolean isChargingByUsb = chargingBy == BatteryManager.BATTERY_PLUGGED_USB;
boolean isChargingByAc = chargingBy == BatteryManager.BATTERY_PLUGGED_AC;
if(intent.getAction().equals(Intent.ACTION_POWER_CONNECTED))
{
time = new Time();
time.setToNow();
shour = time.hour;
sminutee = time.minute;
prefs.edit().putInt("shour", shour).commit();
prefs.edit().putInt("sminute", sminutee).commit();
statusBat += "Power Connected \n";
}
else if(intent.getAction().equals(Intent.ACTION_POWER_DISCONNECTED))
{
time = new Time();
time.setToNow();
ehour = time.hour;
eminutee = time.minute;
prefs.edit().putInt("ehour", ehour).commit();
prefs.edit().putInt("eminute", eminutee).commit();
statusBat += "Power Disconnected \n";
}
int eHour = prefs.getInt("ehour", 0);
int sHour = prefs.getInt("shour", 0);
int eMinute = prefs.getInt("eminutee", 0);
int sMinute = prefs.getInt("sminutee", 0);
int fHour = eHour - sHour;
int fMinute = eMinute - sMinute;
//statusBat += "Total ChargingTime : "+fHour+":"+fMinute+"\n";
batteryStatInfo.setText(statusBat);
//batteryStatImage.setImageResource(icon);
};
};
but i am not getting the result....and my app crashes all the time......is there any other way to do it??
the errors :
03-03 13:04:32.910: E/AndroidRuntime(28227): FATAL EXCEPTION: main
03-03 13:04:32.910: E/AndroidRuntime(28227): java.lang.RuntimeException: Error receiving broadcast Intent { act=android.intent.action.BATTERY_CHANGED flg=0x60000010 (has extras) } in com.rhs.systmenetworkstat.BatteryStatus$1#419261e0
03-03 13:04:32.910: E/AndroidRuntime(28227): at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:798)
03-03 13:04:32.910: E/AndroidRuntime(28227): at android.os.Handler.handleCallback(Handler.java:800)
03-03 13:04:32.910: E/AndroidRuntime(28227): at android.os.Handler.dispatchMessage(Handler.java:100)
03-03 13:04:32.910: E/AndroidRuntime(28227): at android.os.Looper.loop(Looper.java:194)
03-03 13:04:32.910: E/AndroidRuntime(28227): at android.app.ActivityThread.main(ActivityThread.java:5410)
03-03 13:04:32.910: E/AndroidRuntime(28227): at java.lang.reflect.Method.invokeNative(Native Method)
03-03 13:04:32.910: E/AndroidRuntime(28227): at java.lang.reflect.Method.invoke(Method.java:525)
03-03 13:04:32.910: E/AndroidRuntime(28227): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
03-03 13:04:32.910: E/AndroidRuntime(28227): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
03-03 13:04:32.910: E/AndroidRuntime(28227): at dalvik.system.NativeStart.main(Native Method)
03-03 13:04:32.910: E/AndroidRuntime(28227): Caused by: java.lang.NullPointerException
03-03 13:04:32.910: E/AndroidRuntime(28227): at com.rhs.systmenetworkstat.BatteryStatus$1.onReceive(BatteryStatus.java:139)
03-03 13:04:32.910: E/AndroidRuntime(28227): at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:788)
03-03 13:04:32.910: E/AndroidRuntime(28227): ... 9 more
private final BroadcastReceiver receiver = new BroadcastReceiver() {
#SuppressWarnings("deprecation")
#Override
public void onReceive(final Context context, Intent intent) {
String action = intent.getAction();
if(action.equals(Intent.ACTION_POWER_CONNECTED)) {
// Do something when power connected
//save time in proper format in preference or anywhere
}
else if(action.equals(Intent.ACTION_POWER_DISCONNECTED)) {
// Do something when power disconnected
//take the time differene between connted time that
// was saved and current time and dispay it
tv.setText(time_differenece);
}
}
};
IntentFilter filter = new IntentFilter();
filter.addAction("android.intent.action.ACTION_POWER_CONNECTED");
filter.addAction("android.intent.action.ACTION_POWER_DISCONNECTED");
registerReceiver(receiver, filter);
I am trying to use Voice Recognition on Android. Following is my code.
This is the code of the Button that is responsible to start speech recognition.
speak.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "City Name Please?");
startActivityForResult(intent, REQUEST_CODE);
}});
Here is a onActivityResult method.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
ArrayList<String> matches_Text = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
Log.v("Results", matches_Text.get(0).toString());
//Update EditText cityname here
String normalized_cityname = matches_Text.get(0).toString().trim();
normalized_cityname = normalized_cityname.replace(" ","%20");
try {
getResponseString("http://api.openweathermap.org/data/2.5/weather?q="+normalized_cityname+"&units=metric", true);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
The code worked ok but there are two problems I am encountering now and I am afraid that they may be related.
If I try to update text in an EditText instance cityname using cityname.setText(matches_Text.get(0).toString()), it crashes the app.
If I hit the speak button now, the google voice dialog comes up but shows can't reacg google at the moment.
Please suggest what can I do?
Adding the getResponseString method also.
public void getResponseString(String Url, boolean IsCalledOnVoiceInput) throws IOException, JSONException {
String temperature="";
String city;
String country;
String weather_main, weather_description;
MyAsyncTask xxx = new MyAsyncTask();
try {
String responseString = xxx.execute(Url).get();
TextView txtTemp = (TextView)findViewById(R.id.txt_temp);
TextView txtCity = (TextView)findViewById(R.id.txt_CityName);
TextView txtWeatherMain = (TextView)findViewById(R.id.textView2);
TextView txtWeatherDescription = (TextView)findViewById(R.id.textView3);
JSONObject reader = new JSONObject(responseString);
JSONObject main = reader.getJSONObject("main");
temperature = main.getString("temp");
Log.v("temperarure",temperature);
city = reader.getString("name");
Log.v("city",city);
JSONObject sys = reader.getJSONObject("sys");
country = sys.getString("country");
Log.v("country",country);
JSONArray weather = reader.getJSONArray("weather");
JSONObject weather_obj = weather.getJSONObject(0);
weather_main = weather_obj.getString("main");
weather_description = weather_obj.getString("description");
txtTemp.setText(temperature+" °C");
txtCity.setText(city+" ("+country+")");
txtWeatherMain.setText(weather_main);
txtWeatherDescription.setText(weather_description);
if(IsCalledOnVoiceInput)
Speak_Weather_Data(city,temperature,weather_main,weather_description);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (JSONException e){
e.printStackTrace();
}
}
Here is the log output
12-24 13:36:06.050 12164-12164/samarth.learning.http D/dalvikvm﹕ Late-enabling CheckJNI
12-24 13:36:06.300 12164-12164/samarth.learning.http D/Network﹕ Network
12-24 13:36:06.300 12164-12164/samarth.learning.http V/Lat﹕ 28.8331443
12-24 13:36:06.300 12164-12164/samarth.learning.http V/Long﹕ 78.7717138
12-24 13:36:06.360 12164-12164/samarth.learning.http D/libEGL﹕ loaded /vendor/lib/egl/libEGL_adreno.so
12-24 13:36:06.370 12164-12164/samarth.learning.http D/libEGL﹕ loaded /vendor/lib/egl/libGLESv1_CM_adreno.so
12-24 13:36:06.380 12164-12164/samarth.learning.http D/libEGL﹕ loaded /vendor/lib/egl/libGLESv2_adreno.so
12-24 13:36:06.380 12164-12164/samarth.learning.http I/Adreno-EGL﹕ <qeglDrvAPI_eglInitialize:316>: EGL 1.4 QUALCOMM build: (CL4169980)
OpenGL ES Shader Compiler Version: 17.01.10.SPL
Build Date: 11/04/13 Mon
Local Branch:
Remote Branch:
Local Patches:
Reconstruct Branch:
12-24 13:36:06.430 12164-12164/samarth.learning.http D/OpenGLRenderer﹕ Enabling debug mode 0
12-24 13:36:06.531 12164-12164/samarth.learning.http E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
12-24 13:36:06.531 12164-12164/samarth.learning.http E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
12-24 13:36:08.232 12164-12164/samarth.learning.http W/IInputConnectionWrapper﹕ showStatusIcon on inactive InputConnection
12-24 13:36:18.844 12164-12164/samarth.learning.http V/Results﹕ new delhi
12-24 13:36:18.844 12164-12164/samarth.learning.http D/AndroidRuntime﹕ Shutting down VM
12-24 13:36:18.844 12164-12164/samarth.learning.http W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x4157c8b0)
12-24 13:36:18.854 12164-12164/samarth.learning.http E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1234, result=-1, data=Intent { (has extras) }} to activity {samarth.learning.http/samarth.learning.http.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.deliverResults(ActivityThread.java:3462)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3505)
at android.app.ActivityThread.access$1100(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1346)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:5225)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:741)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at samarth.learning.http.MainActivity.onActivityResult(MainActivity.java:160)
at android.app.Activity.dispatchActivityResult(Activity.java:5322)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3458)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3505)
at android.app.ActivityThread.access$1100(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1346)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:5225)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:741)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)
12-24 13:36:22.558 12164-12164/samarth.learning.http I/Process﹕ Sending signal. PID: 12164 SIG: 9
is this what you mean?
i think matches_Text is sometimes NULL?! how about adding an
if(matches_Text == null){
Log.v("Results","matches_Text is NULL!");
return;
}
add above code just after ArrayList<String> matches_Text = da...
I keep getting an error when I launch an activity, at first it was null pointer exception but now I have no idea what the error is and its just not working anymore
Logcat:
02-18 13:15:28.885: D/dalvikvm(328): GC_EXTERNAL_ALLOC freed 50K, 53% free 2553K/5379K, external 2730K/3266K, paused 115ms
02-18 13:15:29.762: D/dalvikvm(328): GC_EXTERNAL_ALLOC freed 1K, 53% free 2552K/5379K, external 6764K/8447K, paused 51ms
02-18 13:15:45.312: D/dalvikvm(328): GC_EXTERNAL_ALLOC freed 11K, 52% free 2583K/5379K, external 8695K/10350K, paused 46ms
02-18 13:15:45.582: D/AndroidRuntime(328): Shutting down VM
02-18 13:15:45.582: W/dalvikvm(328): threadid=1: thread exiting with uncaught exception (group=0x40015560)
02-18 13:15:45.592: E/AndroidRuntime(328): FATAL EXCEPTION: main
02-18 13:15:45.592: E/AndroidRuntime(328): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.connectfour/com.example.connectfour.ScoreActivity}: java.lang.NullPointerException
02-18 13:15:45.592: E/AndroidRuntime(328): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
02-18 13:15:45.592: E/AndroidRuntime(328): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
02-18 13:15:45.592: E/AndroidRuntime(328): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
02-18 13:15:45.592: E/AndroidRuntime(328): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
02-18 13:15:45.592: E/AndroidRuntime(328): at android.os.Handler.dispatchMessage(Handler.java:99)
02-18 13:15:45.592: E/AndroidRuntime(328): at android.os.Looper.loop(Looper.java:123)
02-18 13:15:45.592: E/AndroidRuntime(328): at android.app.ActivityThread.main(ActivityThread.java:3683)
02-18 13:15:45.592: E/AndroidRuntime(328): at java.lang.reflect.Method.invokeNative(Native Method)
02-18 13:15:45.592: E/AndroidRuntime(328): at java.lang.reflect.Method.invoke(Method.java:507)
02-18 13:15:45.592: E/AndroidRuntime(328): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
02-18 13:15:45.592: E/AndroidRuntime(328): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-18 13:15:45.592: E/AndroidRuntime(328): at dalvik.system.NativeStart.main(Native Method)
02-18 13:15:45.592: E/AndroidRuntime(328): Caused by: java.lang.NullPointerException
02-18 13:15:45.592: E/AndroidRuntime(328): at com.example.connectfour.Database.getScores(Database.java:57)
02-18 13:15:45.592: E/AndroidRuntime(328): at com.example.connectfour.ScoreActivity$MyCursorAdapter.<init>(ScoreActivity.java:21)
02-18 13:15:45.592: E/AndroidRuntime(328): at com.example.connectfour.ScoreActivity.onCreate(ScoreActivity.java:49)
02-18 13:15:45.592: E/AndroidRuntime(328): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-18 13:15:45.592: E/AndroidRuntime(328): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
02-18 13:15:45.592: E/AndroidRuntime(328): ... 11 more
02-18 13:15:54.303: I/Process(328): Sending signal. PID: 328 SIG: 9
Code
private static class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE" + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " INTEGER);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public Database(Context context) {
ourContext = context;
}
public Database open() {
ourHelper = new DBHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
public Cursor getScores() {
return ourDatabase.rawQuery("SELECT * FROM "+DATABASE_TABLE, null); //No Parameter
}
}
Code Score Activity: This is score activity line 21 is where the super thing is:
#SuppressWarnings("deprecation")
public MyCursorAdapter(Context context) {
super(context, new Database(context).getScores());
scoreIdx = getCursor().getColumnIndex(Database.KEY_NAME);
// TODO Auto-generated constructor stub
}
When you create your Database class you still have not instanciated the ourDatabase variable.
So when you're doing getScores you are going to have a NPE.
Just try to open() it before.
You have not initialized ourDatabase. first initialize it by calling open()...
public MyCursorAdapter(Context context) {
super(context, new Database(context).open().getScores(););
scoreIdx = getCursor().getColumnIndex(Database.KEY_NAME);
// TODO Auto-generated constructor stub
}
Try this.
public Database open() {
ourHelper = new DBHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
public Cursor getScores() {
ourDatabase = open();
return ourDatabase.rawQuery("SELECT * FROM "+DATABASE_TABLE, null); //No Parameter
close() ;
}
Here, when you call getScores, you db will be created and assigned to ourDatabase which then can be used easily. Let me know if this works.