Error in fetching data from database table - java

I am making an android app. and am trying to fetching data from column, name and score from
the database table but getting this error at run time,
Sorry this application has stopped unexpectedly.
This is my Code from Database Class,
public long addscore(String name, int score)
{
ContentValues values = new ContentValues();
values.put(KEY_name, name);
values.put(KEY_score, score);
// Inserting Row
return db.insert(DATABASE_TABLE, null, values);
}
public Cursor getScore(long rowId) throws SQLException
{
Cursor mCursor = db.query(true,DATABASE_TABLE, new String[] {
KEY_scoreid,KEY_name,KEY_score },,KEY_scoreid + "="
+ rowid,null,null,null,null,null);
if (mCursor != null)
{
mCursor.moveToFirst();
}
return mCursor;
}
And this is the code of class from where i m trying to
fetch the Data from Database table (Highscore.java),
public class Highscore extends Activity
{
TextView name1,name2,name3,name4,name5,score1,score2,score3,score4,score5;
DBAdapter db1;
Cursor c;
int id;
String n1,n2,n3,n4,n5;
String s1,s2,s3,s4,s5;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.highscore);
Button backbtn=(Button)findViewById(R.id.backbtn);
OnClickListener listener=new OnClickListener()
{
public void onClick(View v)
{
Intent i=new Intent(Highscore.this,MainActivity.class);
startActivity(i);
finish();
}
};
backbtn.setOnClickListener(listener);
id=1;
name1=(TextView)findViewById(R.id.name1);
score1=(TextView)findViewById(R.id.score1);
db1=new DBAdapter(this);
db1.open();
c=db1.getScore(1);
n1=c.getString(1);
name1.setText(n1);
s1=c.getString(2);
score1.setText(s1);
c=db1.getScore(2);
n2=c.getString(1);
name2.setText(n2);
s2=c.getString(2);
score2.setText(s2);
c=db1.getScore(3);
n3=c.getString(1);
name3.setText(n3);
s3=c.getString(2);
score3.setText(s3);
id++;
c=db1.getScore(4);
n4=c.getString(1);
name4.setText(n4);
s4=c.getString(2);
score4.setText(s4);
id++;
c=db1.getScore(5);
n5=c.getString(1);
name5.setText(n5);
s5=c.getString(2);
score5.setText(s5);
c.deactivate();
c.close();
db1.close();
}
}
This time i am only fetching 5 names and scores.
Here's my Logcat Error,
09-19 12:01:36.046: D/AndroidRuntime(455): Shutting down VM
09-19 12:01:36.046: W/dalvikvm(455): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
09-19 12:01:36.066: E/AndroidRuntime(455): FATAL EXCEPTION: main
09-19 12:01:36.066: E/AndroidRuntime(455): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.quizapp/com.example.quizapp.Highscore}: java.lang.NullPointerException
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.os.Handler.dispatchMessage(Handler.java:99)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.os.Looper.loop(Looper.java:123)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.ActivityThread.main(ActivityThread.java:4627)
09-19 12:01:36.066: E/AndroidRuntime(455): at java.lang.reflect.Method.invokeNative(Native Method)
09-19 12:01:36.066: E/AndroidRuntime(455): at java.lang.reflect.Method.invoke(Method.java:521)
09-19 12:01:36.066: E/AndroidRuntime(455): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
09-19 12:01:36.066: E/AndroidRuntime(455): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
09-19 12:01:36.066: E/AndroidRuntime(455): at dalvik.system.NativeStart.main(Native Method)
09-19 12:01:36.066: E/AndroidRuntime(455): Caused by: java.lang.NullPointerException
09-19 12:01:36.066: E/AndroidRuntime(455): at com.example.quizapp.Highscore.onCreate(Highscore.java:59)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
09-19 12:01:36.066: E/AndroidRuntime(455): ... 11 more
If you people are not getting any thing from my question so please ask..
Please help me to Solve out the Error.
Thanks in Advance

From what I see you problem is not in the database connection, you have some untreated exceptions. You have a NULL pointer exception also in onCreate(Highscore.java:59)
You can do a thing: comment parts of the code until you get a working app(that does nothing) and then uncomment until you find the exact code that crashes the app, it is easy to do and usually you will find the line that is problematic
Good luck

Use this code insted of your.....
public Cursor getScore(long rowId) throws SQLException
{
Cursor mCursor = db.query(true,DATABASE_TABLE, new String[] {
KEY_scoreid,KEY_name,KEY_score },KEY_scoreid + " ='"
+ rowid + "'",null,null,null,null,null);
if (mCursor != null)
{
mCursor.moveToFirst();
}
return mCursor;
}

Related

Converter application error on Android

Hello guys I am making an Android app that convert from binary to decimal and I have made a class called Binary and a class called Decimal and a function in the Binary class that convert from decimal to binary
public Binary DtoB(Decimal decimal)
{
String temp = null;
do
{
if(decimal.decimal%2!=0)
temp+='1';
else
temp+='0';
decimal.decimal/=2;
}while(decimal.decimal>0);
while(temp.length()%4!=0)
temp+='0';
for(int i=temp.length()-1;i>=0;i--)
{
this.bn+=temp.charAt(i);
}
return this;
}
and in the activity there's a button that converts, but when I test and press on the button the app breaks
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
d1.decimal=Integer.parseInt(e1.getText().toString());
b.DtoB(d1);
t1.setText(b.bn);
}
});
can any one help me please ???
Here is the logcat:
10-26 09:16:15.831: E/AndroidRuntime(280): FATAL EXCEPTION: main
10-26 09:16:15.831: E/AndroidRuntime(280): java.lang.NullPointerException
10-26 09:16:15.831: E/AndroidRuntime(280): at com.example.converter.MainActivity$1.onClick(MainActivity.java:34)
10-26 09:16:15.831: E/AndroidRuntime(280): at android.view.View.performClick(View.java:2408)
10-26 09:16:15.831: E/AndroidRuntime(280): at android.view.View$PerformClick.run(View.java:8816)
10-26 09:16:15.831: E/AndroidRuntime(280): at android.os.Handler.handleCallback(Handler.java:587)
10-26 09:16:15.831: E/AndroidRuntime(280): at android.os.Handler.dispatchMessage(Handler.java:92)
10-26 09:16:15.831: E/AndroidRuntime(280): at android.os.Looper.loop(Looper.java:123) 10-26 09:16:15.831: E/AndroidRuntime(280): at android.app.ActivityThread.main(ActivityThread.java:4627)
10-26 09:16:15.831: E/AndroidRuntime(280): at java.lang.reflect.Method.invokeNative(Native Method) 10-26 09:16:15.831: E/AndroidRuntime(280): at java.lang.reflect.Method.invoke(Method.java:521)
Try this...!
public class BinaryToDecimal {
public int getDecimalFromBinary(int binary){
int decimal = 0;
int power = 0;
while(true){
if(binary == 0){
break;
} else {
int tmp = binary%10;
decimal += tmp*Math.pow(2, power);
binary = binary/10;
power++;
}
}
return decimal;
}
public static void main(String a[]){
BinaryToDecimal bd = new BinaryToDecimal();
System.out.println("11 ===> "+bd.getDecimalFromBinary(11));
System.out.println("110 ===> "+bd.getDecimalFromBinary(110));
System.out.println("100110 ===> "+bd.getDecimalFromBinary(100110));
}
}
check variable all are initialize perfectly . because some time objectc are created but it is null so can't work and throw java.lang.NullPointerException .....
b1 , d1 , b ,t1

Retrieve SQLite data in edit text from Spinner selected item in Android

I have spinner in Activity and edittext's. When i run the app I'm getting warning of nullPointerException.I dosen't retrieve the SQLite data in edit text in onCreate().Can someone help me.
Here is my code.
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.delete_entry);
databaseHelper = new DatabaseHelper(this);
databaseHelper.onOpen(db);
spinner_searchByEmpName = (Spinner)findViewById(R.id.searchByEmpName);
loadSerachBYProject() ;
spinner_searchByEmpName.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
selectedEmployeeName = spinner_searchByEmpName.getSelectedItem().toString().trim();
System.out.println("selectedProjectName " + selectedEmployeeName);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
etEmpName=(EditText)findViewById(R.id.Delete_editText_StaffEmployee_Name);
etDepartment=(EditText)findViewById(R.id.Delete_editText_Department);
etDesignation=(EditText)findViewById(R.id.Delete_editText_Designation);
try {
Cursor cursor = db.rawQuery("SELECT staff_employee_id, staff_emp_name, department, designation FROM employee_details WHERE staff_emp_name = ?",
new String[] { "" + selectedEmployeeName });
etEmpName.setText(cursor.getString(cursor
.getColumnIndex("staff_emp_name")));
etDepartment.setText(cursor.getString(cursor
.getColumnIndex("department")));
etDesignation.setText(cursor.getString(cursor
.getColumnIndex("designation")));
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
private void loadSerachBYProject()
{
DatabaseHelper databaseHelper = new DatabaseHelper(getApplicationContext());
// Spinner Drop down elements
List<String> projectsName = databaseHelper.getAllEmployeeName();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, projectsName);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner_searchByEmpName.setAdapter(dataAdapter);
}
}
Thanks in Advance.
Here is My Log cat error info
06-26 18:08:09.073: W/System.err(601): java.lang.NullPointerException
06-26 18:08:09.083: W/System.err(601): at com.employee_review.Update_Entry.onCreate(Update_Entry.java:68)
06-26 18:08:09.083: W/System.err(601): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
06-26 18:08:09.083: W/System.err(601): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
06-26 18:08:09.083: W/System.err(601): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
06-26 18:08:09.092: W/System.err(601): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
06-26 18:08:09.092: W/System.err(601): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
06-26 18:08:09.103: W/System.err(601): at android.os.Handler.dispatchMessage(Handler.java:99)
06-26 18:08:09.103: W/System.err(601): at android.os.Looper.loop(Looper.java:123)
06-26 18:08:09.113: W/System.err(601): at android.app.ActivityThread.main(ActivityThread.java:3683)
06-26 18:08:09.123: W/System.err(601): at java.lang.reflect.Method.invokeNative(Native Method)
06-26 18:08:09.133: W/System.err(601): at java.lang.reflect.Method.invoke(Method.java:507)
06-26 18:08:09.133: W/System.err(601): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
06-26 18:08:09.133: W/System.err(601): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
06-26 18:08:09.133: W/System.err(601): at dalvik.system.NativeStart.main(Native Method)
Try this , i guess
if(cursor!=null){
etEmpName.setText(cursor.getString(cursor
.getColumnIndex("staff_emp_name")));
etDepartment.setText(cursor.getString(cursor
.getColumnIndex("department")));
etDesignation.setText(cursor.getString(cursor
.getColumnIndex("designation")));
}
db is never initialized. It must be initialized in onCreate(), as that's the first method that is run in an Activity. I see this:
databaseHelper = new DatabaseHelper(this);
databaseHelper.onOpen(db);
I'm guessing you really should have this:
databaseHelper = new DatabaseHelper(this);
db=databaseHelper.getReadableDatabase();

Search Listview is retrieving error..and I don't know why

The code below was working perfectly. To be honest I don't even think I changed something. It stopped working. I have a custom Listview, and the error is on search inside that custom listview. I created a custom Adapter, etc.
// Products Activity:
listView = (ListView) findViewById(R.id.product_listview);
inputSearch = (EditText) findViewById(R.id.inputSearch);
adapter = new itemAdapter(this,R.layout.row, display_products);
listView.setAdapter(adapter);
/**
* Enabling Search Filter
* */
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = inputSearch.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
And this is filter on custom adapter (I didn't put the getView method because it's working..but if you need let me know.):
public class itemAdapter extends ArrayAdapter<oc_product_display> {
private final Context context;
private final List<oc_product_display> lista;
private ArrayList<oc_product_display> arraylist;
private final int rowResourceId;
public itemAdapter(Context context, int textViewResourceId, List<oc_product_display> objects) {
super(context, textViewResourceId, objects);
this.context = context;
this.lista = objects;
this.rowResourceId = textViewResourceId;
this.arraylist = new ArrayList<oc_product_display>();
this.arraylist.addAll(lista);
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
lista.clear();
if (charText.length() == 0) {
lista.addAll(arraylist);
} else {
for (oc_product_display wp : arraylist) {
if (wp.get_name().toLowerCase(Locale.getDefault())
.contains(charText)) {
lista.add(wp);
}
}
}
notifyDataSetChanged();
}
}
LogCat
And this is the error: 10-04 06:29:08.576: E/AndroidRuntime(10284):
FATAL EXCEPTION: main 10-04 06:29:08.576: E/AndroidRuntime(10284):
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.myExample/com.example.myExample.ProductsActivity}:
java.lang.NullPointerException 10-04 06:29:08.576:
E/AndroidRuntime(10284): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
10-04 06:29:08.576: E/AndroidRuntime(10284): at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
10-04 06:29:08.576: E/AndroidRuntime(10284): at
android.app.ActivityThread.access$600(ActivityThread.java:141) 10-04
06:29:08.576: E/AndroidRuntime(10284): at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
10-04 06:29:08.576: E/AndroidRuntime(10284): at
android.os.Handler.dispatchMessage(Handler.java:99) 10-04
06:29:08.576: E/AndroidRuntime(10284): at
android.os.Looper.loop(Looper.java:137) 10-04 06:29:08.576:
E/AndroidRuntime(10284): at
android.app.ActivityThread.main(ActivityThread.java:5103) 10-04
06:29:08.576: E/AndroidRuntime(10284): at
java.lang.reflect.Method.invokeNative(Native Method) 10-04
06:29:08.576: E/AndroidRuntime(10284): at
java.lang.reflect.Method.invoke(Method.java:525) 10-04 06:29:08.576:
E/AndroidRuntime(10284): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
10-04 06:29:08.576: E/AndroidRuntime(10284): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 10-04
06:29:08.576: E/AndroidRuntime(10284): at
dalvik.system.NativeStart.main(Native Method) 10-04 06:29:08.576:
E/AndroidRuntime(10284): Caused by: java.lang.NullPointerException
10-04 06:29:08.576: E/AndroidRuntime(10284): at
com.example.myExample.ProductsActivity.onCreate(ProductsActivity.java:46)
10-04 06:29:08.576: E/AndroidRuntime(10284): at
android.app.Activity.performCreate(Activity.java:5133) 10-04
06:29:08.576: E/AndroidRuntime(10284): at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
10-04 06:29:08.576: E/AndroidRuntime(10284): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
10-04 06:29:08.576: E/AndroidRuntime(10284): ... 11 more
As you may see it gives on line:
10-04 06:29:08.576: E/AndroidRuntime(10284): at com.example.myExample.ProductsActivity.onCreate(ProductsActivity.java:46)
Which is:
inputSearch.addTextChangedListener(new TextWatcher() {
If I remove the option of search, the products are displayed and I don't get any error.
Thanks.
Logcat says it all:
Caused by: java.lang.NullPointerException at com.example.myExample.ProductsActivity.onCreate(ProductsActivity.java:46)
Check this line if it is null or not.
If that line is the one you declared on question... Then probably your "inputSearch" is null. Be sure that you find this view on correct layout.

Activity closes when trying to asyncronously connect to twitter

I have been trying to program a twitter client for Android (using twitter4j). So far the idea is to have a simple GUI, and if there is not a file with the OAuth token in the SD Card, connect to the Twitter API using AsyncTask, get the URL for the authorization and open the default browser. However, the browser never runs. Depending on the different modifications I have made trying to fix this, either the Activity starts normally but the browser never starts or the Activity crashes. I have come to a point of a a little of frustation and confussion. Can someone point out what's wrong with my code?
public class StatusActivity extends Activity {
private static final String TAG = "StatusActivity";
EditText editText;
Button updateButton;
File oauthfile = null;
public Context context = getApplicationContext();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_status);
Log.d(TAG, "started");
// Find views
editText = (EditText) findViewById(R.id.editText); //
updateButton = (Button) findViewById(R.id.buttonUpdate);
oauthfile = new File("sdcard/auth_file.txt");
//Check if the file with the keys exist
if (oauthfile.exists()==false){
Log.d(TAG, "file not created");
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, "file not created.", Toast.LENGTH_SHORT);
toast.show();
new Authorization(context).execute();
}
}
public void openBrowser (View v){
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);
Log.d(TAG, "onclick");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.status, menu);
return true;
}
}
class Authorization extends AsyncTask <String, Integer, String>{
String url = null;
private Context context;
Authorization(Context context) {
this.context = context.getApplicationContext();
}
public void onPreExecute() {
super.onPreExecute();
Toast.makeText(context, "Invoke onPreExecute()", Toast.LENGTH_SHORT).show();
}
#Override
public String doInBackground(String... params) {
ConfigurationBuilder configBuilder = new ConfigurationBuilder();
configBuilder.setDebugEnabled(true)
//I have eliminated the keys from the question :)
.setOAuthConsumerKey("XXXXXXXXXXXXXX")
.setOAuthConsumerSecret("XXXXXXXXXXXXXXX");
Twitter OAuthTwitter = new TwitterFactory(configBuilder.build()).getInstance();
RequestToken requestToken = null;
AccessToken accessToken = null;
do{
try {
requestToken = OAuthTwitter.getOAuthRequestToken();
url = requestToken.getAuthorizationURL();
}
catch (TwitterException ex) {
ex.printStackTrace();
}
}
while (accessToken==null);
return url;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(context, "Opening browser.", Toast.LENGTH_SHORT).show();
Intent browserIntent = new Intent(Intent.ACTION_ALL_APPS, Uri.parse(url));
context.startActivity(browserIntent);
}
}
I know that at least checks if the file for the tokens exists because the toast "file not created" appears, and that the activity is able to run the browser if I press the button. The app has permissions to write in the SD card and use the Internet. Thanks in advance.
Logcat Trace:
03-28 19:02:32.816: E/AndroidRuntime(278): FATAL EXCEPTION: main
03-28 19:02:32.816: E/AndroidRuntime(278): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.versec.pardinus/com.versec.pardinus.StatusActivity}: java.lang.NullPointerException
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.os.Handler.dispatchMessage(Handler.java:99)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.os.Looper.loop(Looper.java:123)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread.main(ActivityThread.java:4627)
03-28 19:02:32.816: E/AndroidRuntime(278): at java.lang.reflect.Method.invokeNative(Native Method)
03-28 19:02:32.816: E/AndroidRuntime(278): at java.lang.reflect.Method.invoke(Method.java:521)
03-28 19:02:32.816: E/AndroidRuntime(278): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
03-28 19:02:32.816: E/AndroidRuntime(278): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
03-28 19:02:32.816: E/AndroidRuntime(278): at dalvik.system.NativeStart.main(Native Method)
03-28 19:02:32.816: E/AndroidRuntime(278): Caused by: java.lang.NullPointerException
03-28 19:02:32.816: E/AndroidRuntime(278): at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:100)
03-28 19:02:32.816: E/AndroidRuntime(278): at com.versec.pardinus.StatusActivity.<init>(StatusActivity.java:30)
03-28 19:02:32.816: E/AndroidRuntime(278): at java.lang.Class.newInstanceImpl(Native Method)
03-28 19:02:32.816: E/AndroidRuntime(278): at java.lang.Class.newInstance(Class.java:1429)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2577)
03-28 19:02:32.816: E/AndroidRuntime(278): ... 11 more
This is what is causing your crash.
public Context context = getApplicationContext();
You're not even using it when you need it, so you can just get rid of this line.
Btw, something else I noticed while looking at your code is this:
oauthfile = new File("sdcard/auth_file.txt");
Don't take the "sdcard/" path for granted. Use this instead:
File dir = Environment.getExternalStorageDirectory();
File oauthfile = new File(dir, "auth_file.txt");

App Crashes When Reading Contacts

I've got a crash while trying to read the contacts of the user, I thought because it's because of the Emulator, but I want to triple check, as I don't have an android based phone. The Logcat gives an error that, it can't read the row "id" did I incorrectly name that string?
Lastly, how would I implement a dialogue box, to see if the user wants the app to read the contacts?
Thanks so much:)
Code:
private void checkandImportContacts() {
// TODO Auto-generated method stub
SharedPreferences sp = getSharedPreferences(PREFS_CHECK, 0);
String checkfirstime = sp.getString("key3", null);
if(checkfirstime !=null && equals("sdhdasudafdsugdiasgdas38ey98d1diass")) {
finish();
} else {
Cursor cursor = getContacts();
while (cursor.moveToNext()) {
String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
Toast.makeText(getApplicationContext(), displayName, Toast.LENGTH_LONG).show();
}
}
}
private Cursor getContacts() {
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME };
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = ‘" + ("1") + "’";
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME+ " COLLATE LOCALIZED ASC";
return managedQuery(uri, projection, selection, selectionArgs, sortOrder);
}
LogCat:
04-23 16:49:48.288: E/AndroidRuntime(437): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gta5news.bananaphone/com.gta5news.bananaphone.ChatService}: android.database.sqlite.SQLiteException: no such column: ‘1’: , while compiling: SELECT _id, display_name FROM view_contacts_restricted WHERE (in_visible_group = ‘1’) ORDER BY display_name COLLATE LOCALIZED ASC
04-23 16:49:48.288: E/AndroidRuntime(437): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
04-23 16:49:48.288: E/AndroidRuntime(437): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
04-23 16:49:48.288: E/AndroidRuntime(437): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
04-23 16:49:48.288: E/AndroidRuntime(437): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
04-23 16:49:48.288: E/AndroidRuntime(437): at android.os.Handler.dispatchMessage(Handler.java:99)
04-23 16:49:48.288: E/AndroidRuntime(437): at android.os.Looper.loop(Looper.java:123)
04-23 16:49:48.288: E/AndroidRuntime(437): at android.app.ActivityThread.main(ActivityThread.java:4627)
04-23 16:49:48.288: E/AndroidRuntime(437): at java.lang.reflect.Method.invokeNative(Native Method)
04-23 16:49:48.288: E/AndroidRuntime(437): at java.lang.reflect.Method.invoke(Method.java:521)
04-23 16:49:48.288: E/AndroidRuntime(437): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-23 16:49:48.288: E/AndroidRuntime(437): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-23 16:49:48.288: E/AndroidRuntime(437): at dalvik.system.NativeStart.main(Native Method)
04-23 16:49:48.288: E/AndroidRuntime(437): Caused by: android.database.sqlite.SQLiteException: no such column: ‘1’: , while compiling: SELECT _id, display_name FROM view_contacts_restricted WHERE (in_visible_group = ‘1’) ORDER BY display_name COLLATE LOCALIZED ASC
04-23 16:49:48.288: E/AndroidRuntime(437): at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:158)
04-23 16:49:48.288: E/AndroidRuntime(437): at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:114)
04-23 16:49:48.288: E/AndroidRuntime(437): at android.content.ContentProviderProxy.bulkQueryInternal(ContentProviderNative.java:330)
04-23 16:49:48.288: E/AndroidRuntime(437): at android.content.ContentProviderProxy.query(ContentProviderNative.java:366)
04-23 16:49:48.288: E/AndroidRuntime(437): at android.content.ContentResolver.query(ContentResolver.java:245)
04-23 16:49:48.288: E/AndroidRuntime(437): at android.app.Activity.managedQuery(Activity.java:1520)
04-23 16:49:48.288: E/AndroidRuntime(437): at com.gta5news.bananaphone.ChatService.getContacts(ChatService.java:73)
04-23 16:49:48.288: E/AndroidRuntime(437): at com.gta5news.bananaphone.ChatService.checkandImportContacts(ChatService.java:56)
04-23 16:49:48.288: E/AndroidRuntime(437): at com.gta5news.bananaphone.ChatService.onCreate(ChatService.java:46)
04-23 16:49:48.288: E/AndroidRuntime(437): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-23 16:49:48.288: E/AndroidRuntime(437): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
You use the wrong chars in your query
Caused by: android.database.sqlite.SQLiteException: no such column: ‘1’
SQLite tries to interpret the ‘1’ as column name since it is no primitive value. Values in SQLite are surrounded by ', column names by " or nothing.
if that group thing is dynamic do it like this:
int group = 1;
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = ?";
String[] selectionArgs = new String[] { String.valueOf(group) };
The value is automatically wrapped in ' & escaped then. If the value is static you can simply do
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = 1";
String[] selectionArgs = null;
private void getDetails(){
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
String[] projection = new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER };
Cursor names = getContentResolver().query(uri, projection, null, null, null);
int indexName = names.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int indexNumber = names.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
names.moveToFirst();
do {
String name = names.getString(indexName);
Log.e("Name new:", name);
String number = names.getString(indexNumber);
Log.e("Number new:","::"+number);
} while (names.moveToNext());
}
The above retrun all the name and number from from your contact database..

Categories