I am calling the insert function in WordListActivity.java from MainActivity.java has the below code by sending the data that needs to be inserted in database.
getContentResolver().insert gives error.
I have also provided the provider permissions in AndroidManifest.xml
MainActivity.java
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.core.content.ContextCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import android.Manifest;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.example.personaldictionary.adapter.DictionaryAdapter;
import com.example.personaldictionary.database.DictionaryContract;
import com.example.personaldictionary.database.DictionaryDbHelper;
import com.example.personaldictionary.utils.NetworkUtils;
import com.google.android.material.navigation.NavigationView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private static final String LOG_TAG = "MainActivity";
private SQLiteDatabase mDatabase;
private CardView mCardView;
private TextView mWordText;
private TextView mWordDef;
private TextView mWordEtylo;
private DictionaryDbHelper mDbHelper;
WordListActivity wordListActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mToggle = new ActionBarDrawerToggle(this,mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
wordListActivity = new WordListActivity();
mCardView = (CardView) findViewById(R.id.word_card);
mCardView.setVisibility(View.GONE);
mWordText = (TextView) findViewById(R.id.word_text);
mWordDef = (TextView) findViewById(R.id.word_definition);
mWordEtylo = (TextView) findViewById(R.id.word_etymologies);
mDbHelper = new DictionaryDbHelper(this);
mDatabase = mDbHelper.getWritableDatabase();
mCardView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Log.d(LOG_TAG," insertWord called: ");
wordListActivity.insertWord(mWordText.getText().toString(),mWordDef.getText().toString(),mWordEtylo.getText().toString());
return true;
}
});
}
}
WordListActivity.java
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.loader.app.LoaderManager;
import androidx.loader.content.Loader;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.example.personaldictionary.adapter.DictionaryAdapter;
import com.example.personaldictionary.database.DictionaryContract;
import com.example.personaldictionary.database.DictionaryDbHelper;
public class WordListActivity extends AppCompatActivity {
private static final String LOG_TAG = "WordListActivity";
DictionaryAdapter mAdapter;
DictionaryDbHelper mDbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_word_list);
RecyclerView word_rv = (RecyclerView) findViewById(R.id.word_rv);
word_rv.setLayoutManager(new LinearLayoutManager(this));
View emptyView = findViewById(R.id.empty_view);
emptyView.setVisibility(View.GONE);
mDbHelper = new DictionaryDbHelper(this);
mAdapter = new DictionaryAdapter(this,getAllItems());
word_rv.setAdapter(mAdapter);
}
public void insertWord(String word,String word_def,String word_etylo){
Uri newUri = null;
Log.d(LOG_TAG,"insertWord() word: "+word+" word_def: "+word_def+" word_et: "+word_etylo);
ContentValues values = new ContentValues();
values.put(DictionaryContract.DictionaryEntry.COLUMN_WORD,word);
values.put(DictionaryContract.DictionaryEntry.COLUMN_WORD_DEFINITION,word_def);
values.put(DictionaryContract.DictionaryEntry.COLUMN_WORD_ETYMOLOGIES,word_etylo);
Log.d(LOG_TAG,"DictionaryContract.DictionaryEntry.CONTENT_URI: "+DictionaryContract.DictionaryEntry.CONTENT_URI);
Log.d(LOG_TAG,"values: "+values);
newUri = getContentResolver().insert(DictionaryContract.DictionaryEntry.CONTENT_URI, values);
mAdapter.swapCursor(getAllItems());
if (newUri == null) {
Toast.makeText(WordListActivity.this, "Word insert error ", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(WordListActivity.this, "Word insert Success", Toast.LENGTH_SHORT).show();
}
}
private Cursor getAllItems(){
Log.d(LOG_TAG,"getAllItems inside");
String[] projection = {DictionaryContract.DictionaryEntry._ID,
DictionaryContract.DictionaryEntry.COLUMN_WORD,
DictionaryContract.DictionaryEntry.COLUMN_WORD_DEFINITION,
DictionaryContract.DictionaryEntry.COLUMN_WORD_ETYMOLOGIES};
return getContentResolver().query(DictionaryContract.DictionaryEntry.CONTENT_URI,projection,null,null,null);
}
}
DictionaryProvider.java
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.util.Log;
import com.example.personaldictionary.database.DictionaryContract.DictionaryEntry;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
public class DictionaryProvider extends ContentProvider {
private static final String LOG_TAG = "DictionaryProvider";
public DictionaryDbHelper mDbHelper;
/** URI matcher code for the content URI for the dictionary table */
private static final int WORDS = 100;
/** URI matcher code for the content URI for a single word in the dictionary table */
private static final int WORD_ID = 101;
#Override
public boolean onCreate() {
Log.d(LOG_TAG,"onCreate called");
mDbHelper = new DictionaryDbHelper(getContext());
return true;
}
private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static{
Log.d(LOG_TAG,"sUriMatcher called");
sUriMatcher.addURI(DictionaryEntry.CONTENT_AUTHORITY, DictionaryEntry.PATH_WORDS, WORDS);
sUriMatcher.addURI(DictionaryEntry.CONTENT_AUTHORITY, DictionaryEntry.PATH_WORDS+"/#",WORD_ID);
}
#Nullable
#Override
public Cursor query(#NonNull Uri uri, #Nullable String[] projection, #Nullable String selection, #Nullable String[] selectionArgs, #Nullable String sortOrder) {
Log.d(LOG_TAG,"query called");
SQLiteDatabase database = mDbHelper.getReadableDatabase();
Cursor cursor;
int match = sUriMatcher.match(uri);
Log.d(LOG_TAG,"query match: "+match);
switch(match){
case WORDS:
Log.d(LOG_TAG,"match WORDS");
cursor = database.query(DictionaryEntry.TABLE_NAME,projection,selection,selectionArgs,null,null,null,null);
break;
case WORD_ID:
Log.d(LOG_TAG,"match WORD_ID");
selection = DictionaryEntry._ID+"=?";
selectionArgs = new String[]{String.valueOf(ContentUris.parseId(uri))};
cursor = database.query(DictionaryEntry.TABLE_NAME,projection,selection,selectionArgs,null,null,sortOrder,null);
break;
default:
throw new IllegalArgumentException("Cannot query unknown Uri "+uri);
}
cursor.setNotificationUri(getContext().getContentResolver(),uri);
return cursor;
}
#Nullable
#Override
public String getType(#NonNull Uri uri) {
Log.d(LOG_TAG,"getType");
final int match = sUriMatcher.match(uri);
Log.d(LOG_TAG,"getType match: "+match);
switch (match) {
case WORDS:
Log.d(LOG_TAG,"return ProductEntry.CONTENT_LIST_TYPE");
return DictionaryEntry.CONTENT_LIST_TYPE;
case WORD_ID:
Log.d(LOG_TAG,"return ProductEntry.CONTENT_ITEM_TYPE");
return DictionaryEntry.CONTENT_ITEM_TYPE;
default:
throw new IllegalStateException("Unknown URI " + uri + " with match " + match);
}
}
#Nullable
#Override
public Uri insert(#NonNull Uri uri, #Nullable ContentValues values) {
Log.d(LOG_TAG,"insert uri "+ uri +" values: "+values);
final int match = sUriMatcher.match(uri);
Log.d(LOG_TAG,"insert match: "+match);
switch(match){
case WORDS:
Log.d(LOG_TAG,"insertDictionary");
return insertDictionary(uri, values);
default:
throw new IllegalArgumentException("Insertion is not supported for "+uri);
}
}
#Override
public int delete(#NonNull Uri uri, #Nullable String selection, #Nullable String[] selectionArgs) {
Log.d(LOG_TAG,"delete uri:"+ uri+" selection: "+selection+"selectionArgs: "+selectionArgs);
// Get writeable database
SQLiteDatabase database = mDbHelper.getWritableDatabase();
// Track the number of rows that were deleted
int rowsDeleted;
final int match = sUriMatcher.match(uri);
Log.d(LOG_TAG,"delete match:"+ match);
switch (match) {
case WORDS:
Log.d(LOG_TAG,"delete WORDS");
// Delete all rows that match the selection and selection args
rowsDeleted = database.delete(DictionaryEntry.TABLE_NAME, selection, selectionArgs);
break;
case WORD_ID:
Log.d(LOG_TAG,"delete WORD_ID");
// Delete a single row given by the ID in the URI
selection = DictionaryEntry._ID + "=?";
selectionArgs = new String[] { String.valueOf(ContentUris.parseId(uri)) };
rowsDeleted = database.delete(DictionaryEntry.TABLE_NAME, selection, selectionArgs);
break;
default:
throw new IllegalArgumentException("Deletion is not supported for " + uri);
}
// If 1 or more rows were deleted, then notify all listeners that the data at the
// given URI has changed
if (rowsDeleted != 0) {
Log.d(LOG_TAG,"delete rowsDeleted != 0");
getContext().getContentResolver().notifyChange(uri, null);
}
// Return the number of rows deleted
return rowsDeleted;
}
#Override
public int update(#NonNull Uri uri, #Nullable ContentValues values, #Nullable String selection, #Nullable String[] selectionArgs) {
Log.d(LOG_TAG,"update uri: "+uri+" values: "+ values+" selection: "+ selection+" selectionArgs: "+selectionArgs);
final int match = sUriMatcher.match(uri);
Log.d(LOG_TAG,"update match: "+match);
switch (match){
case WORDS:
Log.d(LOG_TAG,"update WORDS");
return updateDictionary(uri, values, selection, selectionArgs);
case WORD_ID:
Log.d(LOG_TAG,"update WORD_ID");
selection = DictionaryEntry._ID+"=?";
selectionArgs = new String[] { String.valueOf(ContentUris.parseId(uri))};
return updateDictionary(uri, values, selection, selectionArgs);
default:
throw new IllegalArgumentException("Update is not supported for "+uri);
}
}
private Uri insertDictionary(Uri uri, ContentValues values){
Log.d(LOG_TAG,"insertDictionary uri: "+uri+" values: "+values);
String word = values.getAsString(DictionaryEntry.COLUMN_WORD);
Log.d(LOG_TAG,"insertDictionary word: "+word);
if (word == null) {
throw new IllegalArgumentException("Dictionary requires a word");
}
String word_def_1 = values.getAsString(DictionaryEntry.COLUMN_WORD_DEFINITION);
Log.d(LOG_TAG,"insertDictionary word_def_1: "+word_def_1);
if (word_def_1 == null) {
throw new IllegalArgumentException("Dictionary requires a word definition");
}
String etymologies = values.getAsString(DictionaryEntry.COLUMN_WORD_ETYMOLOGIES);
Log.d(LOG_TAG,"insertDictionary etymologies: "+etymologies);
SQLiteDatabase db = mDbHelper.getWritableDatabase();
long id = db.insert(DictionaryEntry.TABLE_NAME, null, values);
Log.d(LOG_TAG,"insertDictionary() id "+id);
if(id==-1){
Log.e(LOG_TAG,"Failed to insert row for "+uri);
return null;
}
getContext().getContentResolver().notifyChange(uri,null);
Log.d(LOG_TAG,"return ContentUris.withAppendedId(uri,id): "+ContentUris.withAppendedId(uri,id));
return ContentUris.withAppendedId(uri,id);
}
private int updateDictionary(Uri uri, ContentValues values, String selection, String[] selectionArgs){
if (values.containsKey(DictionaryEntry.COLUMN_WORD)) {
String word = values.getAsString(DictionaryEntry.COLUMN_WORD);
if (word == null) {
throw new IllegalArgumentException("Dictionary requires a word");
}
}
if (values.containsKey(DictionaryEntry.COLUMN_WORD_DEFINITION)) {
// Check that the price is greater than or equal to 0 Rs
String word_def_1 = values.getAsString(DictionaryEntry.COLUMN_WORD_DEFINITION);
if (word_def_1 == null) {
throw new IllegalArgumentException("Dictionary requires a word definition");
}
}
// If there are no values to update, then don't try to update the database
if (values.size() == 0) {
return 0;
}
SQLiteDatabase database = mDbHelper.getWritableDatabase();
int rowsUpdated = database.update(DictionaryEntry.TABLE_NAME, values, selection, selectionArgs);
// If 1 or more rows were updated, then notify all listeners that the data at the
// given URI has changed
Log.d(LOG_TAG,"updateDictionary rowsUpdated: "+rowsUpdated);
if (rowsUpdated != 0) {
getContext().getContentResolver().notifyChange(uri, null);
}
return rowsUpdated;
}
}
Error Logs:
2020-06-14 18:55:15.948 24271-24271/com.example.personaldictionary E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.personaldictionary, PID: 24271
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.ContentResolver android.content.Context.getContentResolver()' on a null object reference
at android.content.ContextWrapper.getContentResolver(ContextWrapper.java:101)
at com.example.personaldictionary.WordListActivity.insertWord(WordListActivity.java:68)
at com.example.personaldictionary.MainActivity$2.onLongClick(MainActivity.java:110)
at android.view.View.performLongClickInternal(View.java:6685)
at android.view.View.performLongClick(View.java:6643)
at android.view.View.performLongClick(View.java:6661)
at android.view.View$CheckForLongPress.run(View.java:25862)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6692)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Why do I get this error?
Related
I have been trying to pass the contact data from my second activity's list view to my main activity's list view, upon clicking the checkbox.But the data doesn't get transferred. How do I fix this?
MainActivity.java
package com.example.artist.sender;
import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Parcelable;
import android.provider.ContactsContract;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.text.Editable;
import android.text.TextUtils;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
import static android.R.id.input;
import static android.app.AlertDialog.*;
public class MainActivity extends AppCompatActivity {
EditText itemText;
Button addButton;
Button sendText;
TextView text;
Button contact;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
itemText = (EditText) findViewById(R.id.editText);
addButton = (Button) findViewById(R.id.button1);
text=(TextView) findViewById(R.id.textView);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (TextUtils.isEmpty(itemText.getText())||(itemText.getText().length()<10)||(itemText.getText().length()>10)) {
itemText.setError("The number is not valid.");
return;
} else {
text.setText(itemText.getText().toString());
itemText.setText("");
return;
}
}
});
Button delete;
delete = (Button) findViewById(R.id.btn2);
delete.setOnClickListener(new AdapterView.OnClickListener() {
#Override
public void onClick(View view) {
int con=text.getLineCount();
if(con==0)
Toast.makeText(MainActivity.this, "No number available to delete", Toast.LENGTH_SHORT).show();
else
text.setText("");
}
});
sendText=(Button) findViewById(R.id.btn3);
sendText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String phoneno = text.getText().toString();
int count = text.getLineCount();
SmsManager smsMgrVar = SmsManager.getDefault();
if (count == 0) {
Toast.makeText(MainActivity.this, "No number available", Toast.LENGTH_SHORT).show();
}
else
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED)
{
try{
smsMgrVar.sendTextMessage(phoneno, null, "Hey There!", null, null);
Toast.makeText(MainActivity.this, "Message Sent",Toast.LENGTH_LONG).show();
}
catch (Exception ErrVar)
{
Toast.makeText(MainActivity.this, "Message Sending Failed", Toast.LENGTH_SHORT).show();
ErrVar.printStackTrace();
}
}
else
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
requestPermissions(new String[]{Manifest.permission.SEND_SMS}, 10);
}
}
}
});
contact =(Button) findViewById(R.id.btn4);
contact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
{
startActivity(new Intent(MainActivity.this,contacts.class));
}
}
});
String tempholder=getIntent().getStringExtra("Listviewclickvalue");
text.setText(tempholder);
}
}
contacts.java
package com.example.artist.sender;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.ArrayList;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import static android.Manifest.permission.READ_CONTACTS;
public class contacts extends MainActivity {
private static final int REQUEST_READ_CONTACTS = 444;
private ListView mListView;
private ProgressDialog pDialog;
private Handler updateBarHandler;
ArrayList<String> contactList;
Cursor cursor;
int counter;
ListView list;
String temp;
TextView itemText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pDialog = new ProgressDialog(contacts.this);
pDialog.setMessage("Reading contacts...");
pDialog.setCancelable(false);
pDialog.show();
mListView = (ListView) findViewById(R.id.list);
updateBarHandler = new Handler();
// Since reading contacts takes more time, let's run it on a separate thread.
new Thread(new Runnable() {
#Override
public void run() {
getContacts();
}
}).start();
// Set onclicklistener to the list item.
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//TODO Do whatever you want with the list data
Toast.makeText(getApplicationContext(), "item clicked : \n" + contactList.get(position), Toast.LENGTH_SHORT).show();
}
});
}
private boolean mayRequestContacts() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true;
}
if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
return true;
}
if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
} else {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
return false;
}
/**
* Callback received when a permissions request has been completed.
*/
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
if (requestCode == REQUEST_READ_CONTACTS) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getContacts();
}
}
}
public void getContacts() {
if (!mayRequestContacts()) {
return;
}
contactList = new ArrayList<String>();
String phoneNumber = null;
// String email = null;
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
/* Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
String DATA = ContactsContract.CommonDataKinds.Email.DATA;*/
StringBuffer output;
ContentResolver contentResolver = getContentResolver();
cursor = contentResolver.query(CONTENT_URI, null, null, null, null);
// Iterate every contact in the phone
if (cursor.getCount() > 0) {
counter = 0;
while (cursor.moveToNext()) {
output = new StringBuffer();
// Update the progress message
updateBarHandler.post(new Runnable() {
public void run() {
pDialog.setMessage("Reading contacts : " + counter++ + "/" + cursor.getCount());
}
});
String contact_id = cursor.getString(cursor.getColumnIndex(_ID));
String name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
output.append("\n First Name:" + name);
//This is to read multiple phone numbers associated with the same contact
Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[]{contact_id}, null);
while (phoneCursor.moveToNext()) {
phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
output.append("\n Phone number:" + phoneNumber);
}
phoneCursor.close();
/* // Read every email id associated with the contact
Cursor emailCursor = contentResolver.query(EmailCONTENT_URI, null, EmailCONTACT_ID + " = ?", new String[]{contact_id}, null);
while (emailCursor.moveToNext()) {
email = emailCursor.getString(emailCursor.getColumnIndex(DATA));
output.append("\n Email:" + email);
}
emailCursor.close();
String columns[] = {
ContactsContract.CommonDataKinds.Event.START_DATE,
ContactsContract.CommonDataKinds.Event.TYPE,
ContactsContract.CommonDataKinds.Event.MIMETYPE,
};*/
String where = ContactsContract.CommonDataKinds.Event.TYPE + "=" + ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY +
" and " + ContactsContract.CommonDataKinds.Event.MIMETYPE + " = '" + ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE + "' and " + ContactsContract.Data.CONTACT_ID + " = " + contact_id;
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME;
/*Cursor birthdayCur = contentResolver.query(ContactsContract.Data.CONTENT_URI, columns, where, selectionArgs, sortOrder);
Log.d("BDAY", birthdayCur.getCount()+"");
if (birthdayCur.getCount() > 0) {
while (birthdayCur.moveToNext()) {
String birthday = birthdayCur.getString(birthdayCur.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE));
output.append("Birthday :" + birthday);
Log.d("BDAY", birthday);
}
}
birthdayCur.close();
}*/
// Add the contact to the ArrayList
contactList.add(output.toString());
}
// ListView has to be updated using a ui thread
runOnUiThread(new Runnable() {
#Override
public void run() {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.contact_text, R.id.text1, contactList);
mListView.setAdapter(adapter);
}
});
// Dismiss the progressbar after 500 millisecondds
updateBarHandler.postDelayed(new Runnable() {
#Override
public void run() {
pDialog.cancel();
}
}, 500);
}
}
//passing the number to the mainactivity's textview through intent
list=(ListView) findViewById(R.id.list);
final String listview[] = new String[list.getCount()];
for (int j = 0; j < list.getCount(); j++) {
View v = list.getChildAt(j);
TextView tv = (TextView) v.findViewById(R.id.text1);
listview[j] = (String) tv.getText();
}
itemText = (TextView) findViewById(R.id.text1);
final String number = itemText.getText().toString();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, listview);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if ((number.matches("[0-9]+"))&&(number.length()==10))
temp = listview[position].toString();
Intent intent = new Intent(contacts.this, MainActivity.class);
intent.putExtra("Listviewclickvalue", temp);
startActivity(intent);
}
}
);
}
}
logcat
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.artist.sender/com.example.artist.sender.contacts}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setOnItemClickListener(android.widget.AdapterView$OnItemClickListener)' on a null object reference
This is the logcat for the error. It keeps showing that the setitemOnClickListener keeps referring to a null object whereas, I've already assigned the listview to its respective id.
EDIT:**I've fixed part of the error, by renaming the setContentView(R.layout.activity_main); in the contacts class to setContentView(R.layout.contacts); But now after that, it shows this error, **java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
If the data in the database, or some other storage, only pass the _id or the location, respectively.
Instead of passing many extras, Android way is, actually, Parcable. Here a nice tutorial from Vogella
public class TestModel implements Parcelable {
String name;
String phoneNumber;
//.....
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.name);
dest.writeString(this.phoneNumber);
}
public static final Parcelable.Creator<TestModel> CREATOR = new Parcelable.Creator<TestModel>() {
#Override
public TestModel createFromParcel(Parcel source) {
return new TestModel(source);
}
#Override
public TestModel[] newArray(int size) {
return new TestModel[size];
}
};
}
I have been trying to pass the contact data from my second activity's list view to my main activity's list view, upon clicking the data.But the app crashes just on clicking the contacts button. How do I fix this?
MainActivity.java
package com.example.artist.sender;
import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Parcelable;
import android.provider.ContactsContract;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.text.Editable;
import android.text.TextUtils;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
import static android.R.id.input;
import static android.app.AlertDialog.*;
public class MainActivity extends AppCompatActivity {
EditText itemText;
Button addButton;
Button sendText;
TextView text;
Button contact;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
itemText = (EditText) findViewById(R.id.editText);
addButton = (Button) findViewById(R.id.button1);
text=(TextView) findViewById(R.id.textView);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (TextUtils.isEmpty(itemText.getText())||(itemText.getText().length()<10)||(itemText.getText().length()>10)) {
itemText.setError("The number is not valid.");
return;
} else {
text.setText(itemText.getText().toString());
itemText.setText("");
return;
}
}
});
Button delete;
delete = (Button) findViewById(R.id.btn2);
delete.setOnClickListener(new AdapterView.OnClickListener() {
#Override
public void onClick(View view) {
int con=text.getLineCount();
if(con==0)
Toast.makeText(MainActivity.this, "No number available to delete", Toast.LENGTH_SHORT).show();
else
text.setText("");
}
});
sendText=(Button) findViewById(R.id.btn3);
sendText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String phoneno = text.getText().toString();
int count = text.getLineCount();
SmsManager smsMgrVar = SmsManager.getDefault();
if (count == 0) {
Toast.makeText(MainActivity.this, "No number available", Toast.LENGTH_SHORT).show();
}
else
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED)
{
try{
smsMgrVar.sendTextMessage(phoneno, null, "Hey There!", null, null);
Toast.makeText(MainActivity.this, "Message Sent",Toast.LENGTH_LONG).show();
}
catch (Exception ErrVar)
{
Toast.makeText(MainActivity.this, "Message Sending Failed", Toast.LENGTH_SHORT).show();
ErrVar.printStackTrace();
}
}
else
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
requestPermissions(new String[]{Manifest.permission.SEND_SMS}, 10);
}
}
}
});
contact =(Button) findViewById(R.id.btn4);
contact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
{
startActivity(new Intent(MainActivity.this,contacts.class));
}
}
});
String tempholder=getIntent().getStringExtra("Listviewclickvalue");
text.setText(tempholder);
}
contacts.java
package com.example.artist.sender;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.ArrayList;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import static android.Manifest.permission.READ_CONTACTS;
public class contacts extends MainActivity {
private static final int REQUEST_READ_CONTACTS = 444;
private ListView mListView;
private ProgressDialog pDialog;
private Handler updateBarHandler;
ArrayList<String> contactList;
Cursor cursor;
int counter;
ListView list;
String temp;
TextView itemText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contacts);
pDialog = new ProgressDialog(contacts.this);
pDialog.setMessage("Reading contacts...");
pDialog.setCancelable(false);
pDialog.show();
mListView = (ListView) findViewById(R.id.list);
updateBarHandler = new Handler();
// Since reading contacts takes more time, let's run it on a separate thread.
new Thread(new Runnable() {
#Override
public void run() {
getContacts();
}
}).start();
// Set onclicklistener to the list item.
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//TODO Do whatever you want with the list data
Toast.makeText(getApplicationContext(), "item clicked : \n" + contactList.get(position), Toast.LENGTH_SHORT).show();
}
});
}
private boolean mayRequestContacts() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true;
}
if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED)
{
return true;
}
if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
} else {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
return false;
}
/**
* Callback received when a permissions request has been completed.
*/
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
if (requestCode == REQUEST_READ_CONTACTS) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getContacts();
}
}
}
public void getContacts() {
if (!mayRequestContacts()) {
return;
}
contactList = new ArrayList<String>();
String phoneNumber = null;
// String email = null;
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
/* Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
String DATA = ContactsContract.CommonDataKinds.Email.DATA;*/
StringBuffer output;
ContentResolver contentResolver = getContentResolver();
cursor = contentResolver.query(CONTENT_URI, null, null, null, null);
// Iterate every contact in the phone
if (cursor.getCount() > 0) {
counter = 0;
while (cursor.moveToNext()) {
output = new StringBuffer();
// Update the progress message
updateBarHandler.post(new Runnable() {
public void run() {
pDialog.setMessage("Reading contacts : " + counter++ + "/" + cursor.getCount());
}
});
String contact_id = cursor.getString(cursor.getColumnIndex(_ID));
String name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
output.append("\n First Name:" + name);
//This is to read multiple phone numbers associated with the same contact
Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[]{contact_id}, null);
while (phoneCursor.moveToNext()) {
phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
output.append("\n Phone number:" + phoneNumber);
}
phoneCursor.close();
/* // Read every email id associated with the contact
Cursor emailCursor = contentResolver.query(EmailCONTENT_URI, null, EmailCONTACT_ID + " = ?", new String[]{contact_id}, null);
while (emailCursor.moveToNext()) {
email = emailCursor.getString(emailCursor.getColumnIndex(DATA));
output.append("\n Email:" + email);
}
emailCursor.close();
String columns[] = {
ContactsContract.CommonDataKinds.Event.START_DATE,
ContactsContract.CommonDataKinds.Event.TYPE,
ContactsContract.CommonDataKinds.Event.MIMETYPE,
};*/
String where = ContactsContract.CommonDataKinds.Event.TYPE + "=" + ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY +
" and " + ContactsContract.CommonDataKinds.Event.MIMETYPE + " = '" + ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE + "' and " + ContactsContract.Data.CONTACT_ID + " = " + contact_id;
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME;
/*Cursor birthdayCur = contentResolver.query(ContactsContract.Data.CONTENT_URI, columns, where, selectionArgs, sortOrder);
Log.d("BDAY", birthdayCur.getCount()+"");
if (birthdayCur.getCount() > 0) {
while (birthdayCur.moveToNext()) {
String birthday = birthdayCur.getString(birthdayCur.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE));
output.append("Birthday :" + birthday);
Log.d("BDAY", birthday);
}
}
birthdayCur.close();
}*/
// Add the contact to the ArrayList
contactList.add(output.toString());
}
// ListView has to be updated using a ui thread
runOnUiThread(new Runnable() {
#Override
public void run() {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.contact_text, R.id.text1, contactList);
mListView.setAdapter(adapter);
}
});
// Dismiss the progressbar after 500 millisecondds
updateBarHandler.postDelayed(new Runnable() {
#Override
public void run() {
pDialog.cancel();
}
}, 500);
}
}
//passing the number to the mainactivity's textview through intent
list=(ListView) findViewById(R.id.list);
final String listview[] = new String[list.getCount()];
for (int j = 0; j < list.getCount(); j++) {
View v = list.getChildAt(j);
TextView tv = (TextView) v.findViewById(R.id.text1);
listview[j] = (String) tv.getText();
}
itemText = (TextView) findViewById(R.id.text1);
final String number = itemText.getText().toString();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, listview);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if ((number.matches("[0-9]+"))&&(number.length()==10))
temp = listview[position].toString();
Intent intent = new Intent(contacts.this, MainActivity.class);
intent.putExtra("Listviewclickvalue", temp);
startActivity(intent);
}
}
);
}
logcat
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at com.example.artist.sender.contacts.getContacts(contacts.java:236)
at com.example.artist.sender.contacts$1.run(contacts.java:57)
at java.lang.Thread.run(Thread.java:818)
This is the logcat for the error. It keeps showing that the findViewById keeps referring to a null object whereas, I've already assigned all the variables to their respective ids.
I want to do the following.
Pick up three to five contacts out of a special group of contacts or all contacts.
In the list it would be nice to show the contact image.
The selected contacts should have the following information (contact-id, first name, the small version of the contact image to save it as a blob in the database)
I found solutions for the different aspects.
-select multiple contacts:
How to obtain the checked rows in a custom view list
-show contacts from one group
getting contacts from a specified group in android
- photo problem
Getting a Photo from a Contact
But I dont know how to put those together. It would be great if someone could help me putting it together.
Thank you very much!
Frank J.
Solved it, but cant post the answer for some hours.
Solution (not prettyfied yet)
package com.pinkpony.frankj.contactpicker2;
import android.app.Activity;
import android.content.ClipData;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
/**
* Created by Frank on 28.07.2014.
*/
public class MainActivity extends Activity implements AdapterView.OnItemClickListener {
List<String> name1 = new ArrayList<String>();
List<String> name2 = new ArrayList<String>();
List<String> phno1 = new ArrayList<String>();
List<String> img1 = new ArrayList<String>();
MyAdapter ma ;
Button select;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadGroups();
//Toast.makeText(MainActivity.this, toString(), Toast.LENGTH_LONG).show();
Log.d("LongValue", toString());
getAllCallLogs(this.getContentResolver());
ListView lv= (ListView) findViewById(R.id.lv);
ma = new MyAdapter();
lv.setAdapter(ma);
lv.setOnItemClickListener(this);
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
// adding
select = (Button) findViewById(R.id.button1);
select.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
StringBuilder checkedcontacts= new StringBuilder();
System.out.println(".............."+ma.mCheckStates.size());
for(int i = 0; i < name1.size(); i++)
{
if(ma.mCheckStates.get(i)==true)
{
checkedcontacts.append(name1.get(i).toString());
checkedcontacts.append("\n");
}
else
{
System.out.println("..Not Checked......"+name1.get(i).toString());
}
}
//Toast.makeText(getApplicationContext(), checkedcontacts, 1000).show();
Toast.makeText(MainActivity.this, checkedcontacts, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
ma.toggle(arg2);
}
public void getAllCallLogs(ContentResolver cr) {
/* 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";
Cursor phones = cr.query(uri, projection, selection, selectionArgs,
sortOrder);
*/
// long groupId = id;
String[] cProjection = { ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID };
Cursor groupCursor = getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
cProjection,
ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID + "= ?" + " AND "
+ ContactsContract.CommonDataKinds.GroupMembership.MIMETYPE + "='"
+ ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE + "'",
new String[] { String.valueOf(6) }, null);
if (groupCursor != null && groupCursor.moveToFirst())
{
do
{
int nameCoumnIndex = groupCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
String name = groupCursor.getString(nameCoumnIndex);
String szFullname=name;
//long contactId = groupCursor.getLong(groupCursor.getColumnIndex(ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID));
long contactId = groupCursor.getLong(groupCursor.getColumnIndex(ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID));
// Log.d("your tag", "contact " + name + ":"+String.valueOf(contactId));
name1.add(name);
phno1.add(String.valueOf(contactId));
boolean foundToken = false;
// IDENTIFY Contact based on name and token
String szLookupKey = "";
Uri lkup = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_FILTER_URI, szFullname);
ContentResolver cr2 = getContentResolver();
Cursor idCursor = getContentResolver().query(lkup, null, null, null, null);
// get all the names
while (idCursor.moveToNext()) {
// get current row/contact ID = ID's are unreliable, so we will go for the lookup key
String szId = idCursor.getString(idCursor.getColumnIndex(ContactsContract.Contacts._ID));
String szName = idCursor.getString(idCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
szLookupKey = idCursor.getString(idCursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
// for this contact ID, search the custom field
Log.d("", "Searching token:" + szId + " Name:" + szName + " LookupKey:" + szLookupKey);
//Log.d(LOG_TAG, "search: "+lid + " key: "+key + " name: "+name);
}
String whereName = ContactsContract.Data.MIMETYPE + " = ? AND " + ContactsContract.CommonDataKinds.StructuredName.CONTACT_ID + " = ?";
String[] whereNameParams = new String[] { ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE, String.valueOf(contactId) };
Cursor nameCur = getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, whereName, whereNameParams, ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);
while (nameCur.moveToNext()) {
String given = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
String family = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
String display = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME));
Log.d("your tag", "Vorname " + ":" + given);
name2.add(given);
}
nameCur.close();
} while (groupCursor.moveToNext());
groupCursor.close();
}
}
class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener
{ private SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView tv1,tv;
ImageView im1;
CheckBox cb;
MyAdapter()
{
mCheckStates = new SparseBooleanArray(name1.size());
mInflater = (LayoutInflater)MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
private void retrieveContactPhoto(Long contactID) {
Bitmap photo = null;
try {
InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(),
ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(contactID)));
if (inputStream != null) {
photo = BitmapFactory.decodeStream(inputStream);
ImageView imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setImageBitmap(photo);
}
assert inputStream != null;
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return name1.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public Bitmap openPhoto(long contactId) {
Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
Uri photoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
Cursor cursor = getContentResolver().query(photoUri,
new String[] {ContactsContract.Contacts.Photo.PHOTO}, null, null, null);
if (cursor == null) {
return null;
}
try {
if (cursor.moveToFirst()) {
byte[] data = cursor.getBlob(0);
if (data != null) {
return BitmapFactory.decodeStream(new ByteArrayInputStream(data));
}
}
} finally {
cursor.close();
}
return null;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = mInflater.inflate(R.layout.row, null);
TextView tv= (TextView) vi.findViewById(R.id.textView1);
// tv1= (TextView) vi.findViewById(R.id.textView2);
im1= (ImageView) vi.findViewById(R.id.imageView1);
Bitmap photo = null;
Long contactID=Long.valueOf(phno1.get(position));
im1.setImageBitmap(openPhoto(contactID));
cb = (CheckBox) vi.findViewById(R.id.checkBox1);
tv.setText(""+ name1.get(position));
// tv1.setText(""+phno1.get(position));//
// retrieveContactPhoto(Long.valueOf(phno1.get(position)));
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener(this);
return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
System.out.println("hello...........");
notifyDataSetChanged();
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
private class GroupInfo {
String id;
String title;
#Override
public String toString() {
return title+ " ("+id+")";
}
public String getId() {
return id;
}
}
List<GroupInfo> groups = new ArrayList<GroupInfo>();
public void loadGroups() {
final String[] GROUP_PROJECTION = new String[] {
ContactsContract.Groups._ID,
ContactsContract.Groups.TITLE,
ContactsContract.Groups.SUMMARY_WITH_PHONES
};
Cursor c = getContentResolver().query(
ContactsContract.Groups.CONTENT_SUMMARY_URI,
GROUP_PROJECTION,
ContactsContract.Groups.DELETED+"!='1' AND "+
ContactsContract.Groups.GROUP_VISIBLE+"!='0' "
,
null,
null);
final int IDX_ID = c.getColumnIndex(ContactsContract.Groups._ID);
final int IDX_TITLE = c.getColumnIndex(ContactsContract.Groups.TITLE);
Map<String,GroupInfo> m = new HashMap<String, GroupInfo>();
while (c.moveToNext()) {
GroupInfo g = new GroupInfo();
g.id = c.getString(IDX_ID);
g.title = c.getString(IDX_TITLE);
int users = c.getInt(c.getColumnIndex(ContactsContract.Groups.SUMMARY_WITH_PHONES));
if (users>0) {
// group with duplicate name?
GroupInfo g2 = m.get(g.title);
if (g2==null) {
m.put(g.title, g);
groups.add(g);
} else {
g2.id+=","+g.id;
}
}
Log.d("LongValue", g.id+g.title);
}
c.close();
}
}
Have a good day. I'm learning Android development so i'm creating a simple CRUD application, right now i have my main activity that has the listview (MarcaActivity) with the next code:
package com.example.crudapp.activity;
import android.app.Activity;
import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.example.crudapp.MarcaCursorAdapter;
import com.example.crudapp.R;
import com.example.crudapp.cp.MarcaCP;
public class MarcaActivity extends Activity implements
LoaderManager.LoaderCallbacks<Cursor> {
MarcaCursorAdapter crsAdap;
ListView lstMarcas;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_marca);
lstMarcas = (ListView)findViewById(R.id.lstMarcas);
lstMarcas.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Intent i = new Intent(MarcaActivity.this, MarcaDetailActivity.class);
Uri todoUri = Uri.parse(MarcaCP.CONTENT_URI + "/" + arg3);
i.putExtra("DET", todoUri);
i.putExtra("ACTION", "EXISTING");
startActivity(i);
}
});
getLoaderManager().initLoader(0, null, this);
fillData();
}
protected void onRestoreInstanceState(Bundle savedInstanceState) {
getLoaderManager().restartLoader(0, null, this);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.insertMnu:
Intent i = new Intent(this, MarcaDetailActivity.class);
i.putExtra("ACTION", "NEW");
startActivityForResult(i, 0);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
/*switch (item.) {
case DELETE_ID:
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
Uri uri = Uri.parse(MarcaCP.CONTENT_URI + "/"
+ info.id);
getContentResolver().delete(uri, null, null);
fillData();
return true;
}*/
return super.onContextItemSelected(item);
}
private void fillData() {
crsAdap = new MarcaCursorAdapter(this, R.layout.template_marcas, null ,
new String[]{MarcaCP.Marca.NOMBRE, MarcaCP.Marca.RANKING}, new int[]{R.id.nomMarca, R.id.rankMarca});
lstMarcas.setAdapter(crsAdap);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.marca, menu);
return true;
}
#Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
return new CursorLoader(this, MarcaCP.CONTENT_URI,
new String[]{MarcaCP.Marca.ID, MarcaCP.Marca.NOMBRE, MarcaCP.Marca.CODIGO, MarcaCP.Marca.RANKING}, null, null, null);
}
#Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
crsAdap.swapCursor(arg1);
}
#Override
public void onLoaderReset(Loader<Cursor> arg0) {
crsAdap.swapCursor(null);
} }
Then, i have the activity that manages the detail view where i can update or add items, called MarcaDetailActivity:
package com.example.crudapp.activity;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.example.crudapp.MarcaCursorAdapter;
import com.example.crudapp.R;
import com.example.crudapp.cp.MarcaCP;
public class MarcaDetailActivity extends Activity {
MarcaCursorAdapter crsAdap;
private Integer idReg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detalle_marca);
Bundle extras = getIntent().getExtras();
if(extras != null && extras.get("ACTION").equals("EXISTING")) //Invocamos fillData
fillData((Uri)extras.get("DET"));
else
cleanForm();
}
public void cleanForm() {
((Button)findViewById(R.id.todo_edit_button)).setVisibility(View.INVISIBLE);
((Button)findViewById(R.id.todo_insert_button)).setVisibility(View.VISIBLE);
}
public void fillData(Uri uri) {
String[] projection = { MarcaCP.Marca.CODIGO,
MarcaCP.Marca.CLASIFICACION, MarcaCP.Marca.NOMBRE, MarcaCP.Marca.RANKING};
//builder.
Cursor cur = getContentResolver().query(uri, projection, null, null, null);
if(cur != null) {
cur.moveToFirst();
((EditText)findViewById(R.id.detNombre)).setText(cur.getString(cur.getColumnIndex(MarcaCP.Marca.NOMBRE)));
((EditText)findViewById(R.id.detCodigo)).setText(cur.getString(cur.getColumnIndex(MarcaCP.Marca.CODIGO)));
setIdReg(cur.getInt(cur.getColumnIndex(MarcaCP.Marca.ID)));
((EditText)findViewById(R.id.todo_edit_button)).setVisibility(View.VISIBLE);
((EditText)findViewById(R.id.todo_insert_button)).setVisibility(View.INVISIBLE);
String clasif = cur.getString(cur.getColumnIndex(MarcaCP.Marca.CLASIFICACION));
int rank = cur.getInt(cur.getColumnIndex(MarcaCP.Marca.RANKING));
Spinner spRnk = ((Spinner)findViewById(R.id.detRanking));
Spinner spClasf = ((Spinner)findViewById(R.id.detClasificacion));
//Buscamos setear los spinners en sus valores
for(short ps = 0; ps < spRnk.getCount(); ps++) {
String tmpRnk = (String)spRnk.getItemAtPosition(ps);
if(tmpRnk.equalsIgnoreCase("" + rank))
spRnk.setSelection(ps);
}
//Buscamos setear los spinners en sus valores
for(short ps = 0; ps < spClasf.getCount(); ps++) {
String tmpClas = (String)spClasf.getItemAtPosition(ps);
if(tmpClas.equalsIgnoreCase(clasif))
spClasf.setSelection(ps);
}
cur.close();
}
}
private boolean validate() {
boolean res = true;
return res;
}
public void guardar(View view) {
if(validate()) {
ContentValues cv = new ContentValues();
cv.put(MarcaCP.Marca.CLASIFICACION, (String)((Spinner)findViewById(R.id.detClasificacion)).getSelectedItem() );
cv.put(MarcaCP.Marca.CODIGO, ((TextView)findViewById(R.id.detCodigo)).getText().toString() );
cv.put(MarcaCP.Marca.NOMBRE, ((TextView)findViewById(R.id.detNombre)).getText().toString() );
cv.put(MarcaCP.Marca.RANKING, Integer.parseInt("" + ((Spinner)findViewById(R.id.detRanking)).getSelectedItem() ));
getContentResolver().insert(MarcaCP.CONTENT_URI, cv);
}
Toast.makeText(MarcaDetailActivity.this, "Registro registrado",
Toast.LENGTH_SHORT).show();
//Refrescamos el grid y cerramos la actividad
//((MarcaActivity)this.getCallingActivity()).refrescarLista()
//getLoaderManager().restartLoader(0, null, MarcaActivity.class);
this.finish();
}
public void regresar() {
Intent i = new Intent(MarcaDetailActivity.this, MarcaActivity.class);
i.putExtra("REFRESH", true);
startActivity(i);
}
public void actualizar(View view) {
if(validate()) {
ContentValues cv = new ContentValues();
cv.put(MarcaCP.Marca.CLASIFICACION, (String)((Spinner)findViewById(R.id.detClasificacion)).getSelectedItem() );
cv.put(MarcaCP.Marca.CODIGO, (String)((TextView)findViewById(R.id.detCodigo)).getText() );
cv.put(MarcaCP.Marca.NOMBRE, (String)((TextView)findViewById(R.id.detNombre)).getText() );
cv.put(MarcaCP.Marca.ID, getIdReg() );
cv.put(MarcaCP.Marca.RANKING, Integer.parseInt("" + ((Spinner)findViewById(R.id.detRanking)).getSelectedItem() ));
getContentResolver().update(MarcaCP.CONTENT_URI, cv, null, null);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.marca, menu);
return true;
}
public Integer getIdReg() {
return idReg;
}
public void setIdReg(Integer idReg) {
this.idReg = idReg;
} }
As you can see in the method guardar of MarcaDetailActivity, first i insert the item using my custom content provider, then i use Toast to show a confirm message, and finally finishing the activity, but when i do that, the listview isn't refreshed via the cursorloader. I read here (stackoverflow) and in other pages that i have to call
getLoaderManager().restartLoader(LIST_ID, null, this);
But in all examples that i found all the stuff (inserting data in the database and refreshing the list) is in the same activity, but in this case i have an activity with the list and the second activity that inserts the item, so i think that i have to call restartLoader from my detail activity, but i don't know how to do that or if that's the right way to do this. I was thinking about saving a reference to the list activity in extras when i create the intent to call the detail activity and have a public method that calls restartLoader but i don't know if that is the best approach. What's the best way to refresh the cursor loader from my detail activity?
And there's my content provider, MarcaCP:
package com.example.crudapp.cp;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import com.example.crudapp.util.ConnHandler;
public class MarcaCP extends ContentProvider {
private static final int TODOS = 10;
private static final int TODO_ID = 20;
public static final Uri CONTENT_URI = Uri.parse("content://provider.marcacp/marcas");
private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
sURIMatcher.addURI("provider.marcacp", "marcas", TODOS);
sURIMatcher.addURI("provider.marcacp", "marcas" + "/#", TODO_ID);
}
public static class Marca {
public static final String TABLA = "MARCA";
public static final String ID = "_id";
public static final String CODIGO = "codigo";
public static final String NOMBRE = "nombre";
public static final String CLASIFICACION = "clasificacion";
public static final String RANKING = "ranking";
}
private ConnHandler conn;
SQLiteDatabase dbObj;
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int uriType = sURIMatcher.match(uri);
int rowsDeleted = 0;
switch (uriType) {
case TODOS:
rowsDeleted = dbObj.delete(Marca.TABLA, selection, selectionArgs);
break;
case TODO_ID:
String id = uri.getLastPathSegment();
if (TextUtils.isEmpty(selection)) {
rowsDeleted = dbObj.delete(Marca.TABLA,
Marca.ID + " = " + id,
null);
} else {
rowsDeleted = dbObj.delete(Marca.TABLA,
Marca.ID + " =" + id
+ " and " + selection,
selectionArgs);
}
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return rowsDeleted;
}
#Override
public String getType(Uri uri) {
// TODO Auto-generated method stub
return null;
}
#Override
public Uri insert(Uri uri, ContentValues values) {
int uriType = sURIMatcher.match(uri);
long id = 0;
switch (uriType) {
case TODOS:
id = dbObj.insert(Marca.TABLA, null, values);
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return Uri.parse("marca/" + id);
}
#Override
public boolean onCreate() {
conn = new ConnHandler(getContext());
dbObj = conn.getDb();
return true;
}
#Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
// Uisng SQLiteQueryBuilder instead of query() method
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
checkColumns(projection);
queryBuilder.setTables(Marca.TABLA);
int uriType = sURIMatcher.match(uri);
switch (uriType) {
case TODOS:
break;
case TODO_ID:
// Digamos para ver el detalle de un registro
queryBuilder.appendWhere(Marca.ID + " = "
+ uri.getLastPathSegment());
break;
default:
throw new IllegalArgumentException("Unknown URIx: " + uri);
}
Cursor cur = queryBuilder.query(dbObj, projection, selection,
selectionArgs, null, null, sortOrder);
return cur;
}
#Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
int uriType = sURIMatcher.match(uri);
int rowsUpdated = 0;
switch (uriType) {
case TODOS:
rowsUpdated = dbObj.update(Marca.TABLA,
values,
selection,
selectionArgs);
break;
case TODO_ID:
String id = uri.getLastPathSegment();
if (TextUtils.isEmpty(selection)) {
rowsUpdated = dbObj.update(Marca.TABLA,
values,
Marca.ID + " =" + id,
null);
} else {
rowsUpdated = dbObj.update(Marca.TABLA,
values,
Marca.ID + " =" + id
+ " and "
+ selection,
selectionArgs);
}
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return rowsUpdated;
}
private void checkColumns(String[] projection) {
/*String[] available = { TodoTable.COLUMN_CATEGORY,
TodoTable.COLUMN_SUMMARY, TodoTable.COLUMN_DESCRIPTION,
TodoTable.COLUMN_ID };
if (projection != null) {
HashSet<String> requestedColumns = new HashSet<String>(Arrays.asList(projection));
HashSet<String> availableColumns = new HashSet<String>(Arrays.asList(available));
// Check if all columns which are requested are available
if (!availableColumns.containsAll(requestedColumns)) {
throw new IllegalArgumentException("Unknown columns in projection");
}
}*/
} }
It's already registered in the AndroidManifest.xml:
<provider android:name=".cp.MarcaCP" android:authorities="provider.marcacp" />
Regards.
Try getContentResolver().notifyChange(MarcaCP.CONTENT_URI, null, false) from the second activity before finishing it.
It's a bit late to answer this.
since in your ContentProvider, you have
getContext().getContentResolver().notifyChange
which is great and correct!
so there is no need to called
getContentResolver().notifyChange(MarcaCP.CONTENT_URI, null, false) from the second activity before finishing it.
the problem is that instead of using getLoaderManager().initLoader
which is deprecated and not life-cycled aware.
try use
LoaderManager.getInstance(this).initLoader
this: is a class that maintains its own android.arch.lifecycle.Lifecycle and android.arch.lifecycle.ViewModelStore. For instance, androidx.fragment.app.FragmentActivity or androidx.fragment.app.Fragment.
so that when you pop back to the first activity and OnResume() called, there is no need to restart the loader again.
P.s. also a great reminder. Do not close any cursor related to the onLoadFinished(#NonNull Loader<Cursor> loader, Cursor cursor)
if doing so will also cause the loader won't update itself after data changed in DB.
There are two errors as indicated on line 28 and the line, could somebody why I am getting these errors
package com.xcxcxc;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.UserDictionary;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
public class UserDict extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.audiolistmain);
}
SimpleCursorAdapter adapter;
ListView audiolist = (ListView) findViewById(R.id.audioList);
String[] mProjection =
{
UserDictionary.Words._ID,
UserDictionary.Words.WORD,
UserDictionary.Words.LOCALE
};
String mSelectionClause = null;
String[] mSelectionArgs = {""};
static final String[] DBFIELDS= {UserDictionary.Words.WORD, UserDictionary.Words.LOCALE};
static final int[] LISTFIELDS = { R.id.dictWord,R.id.locale};
String mSearchString = "m"; //syntax error on token ";" { expected after this token
if (TextUtils.isEmpty(mSearchString)) {
mSelectionClause = null;
mSelectionArgs[0] = "";
} else {
mSelectionClause = UserDictionary.Words.WORD + " = ?";
mSelectionArgs[0] = mSearchString;
}
Cursor mCursor = getContentResolver().query(
UserDictionary.Words.CONTENT_URI,
mProjection,
mSelectionClause,
mSelectionArgs,
null);
if (null == mCursor) {
Log.e("Cursor returned null, query could not be performed","");
} else if (mCursor.getCount() < 1) {
Toast.makeText(this, "nowords"+mSearchString+"found", Toast.LENGTH_LONG).show();
} else {
int[] mWordListItems = { R.id.dictWord, R.id.locale};
String[] mWordListColumns =
{
UserDictionary.Words.WORD,
UserDictionary.Words.LOCALE
};
SimpleCursorAdapter mCursorAdapter = new SimpleCursorAdapter(
getApplicationContext(),
R.layout.row,
mCursor,
DBFIELDS,
LISTFIELDS);
audiolist.setAdapter(mCursorAdapter);
} // syntax error insert } to complete class body
The line immediately following the line you're showing as flagged with the error is code which should be inside a method, but isn't. I'm going to guess that you didn't mean to close onCreate after this line:
setContentView(R.layout.audiolistmain);
and that all the code you've listed here is supposed to be part of that method. Just remove the closing bracket } on the next line, and add two closing brackets at the end of the file, and it should match up.
To fix the second issue you need a closing "}" at the end of the file to finish off the class body.
If you still don't get what #Xono said
remove the { of this
package com.xcxcxc;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.UserDictionary;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
public class UserDict extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.audiolistmain);
} <--------------- THIS ONE
^
|
|
|
|
|
|
|
THIS ONE
And place it at the very bottom....
EDIT:
also add another { to close the class.
package com.xcxcxc;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.UserDictionary;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
public class UserDict extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.audiolistmain);
// "{" ====>> Removed
SimpleCursorAdapter adapter;
ListView audiolist = (ListView) findViewById(R.id.audioList);
String[] mProjection =
{
UserDictionary.Words._ID,
UserDictionary.Words.WORD,
UserDictionary.Words.LOCALE
};
String mSelectionClause = null;
String[] mSelectionArgs = {""};
static final String[] DBFIELDS= {UserDictionary.Words.WORD, UserDictionary.Words.LOCALE};
static final int[] LISTFIELDS = { R.id.dictWord,R.id.locale};
String mSearchString = "m"; //syntax error on token ";" { expected after this token
if (TextUtils.isEmpty(mSearchString)) {
mSelectionClause = null;
mSelectionArgs[0] = "";
} else {
mSelectionClause = UserDictionary.Words.WORD + " = ?";
mSelectionArgs[0] = mSearchString;
}
Cursor mCursor = getContentResolver().query( UserDictionary.Words.CONTENT_URI,
mProjection,
mSelectionClause,
mSelectionArgs,
null);
if (null == mCursor) {
Log.e("Cursor returned null, query could not be performed","");
} else if (mCursor.getCount() < 1) {
Toast.makeText(this, "nowords"+mSearchString+"found", Toast.LENGTH_LONG).show();
} else {
int[] mWordListItems = { R.id.dictWord, R.id.locale};
String[] mWordListColumns =
{
UserDictionary.Words.WORD,
UserDictionary.Words.LOCALE
};
SimpleCursorAdapter mCursorAdapter = new SimpleCursorAdapter(
getApplicationContext(),
R.layout.row,
mCursor,
DBFIELDS,
LISTFIELDS);
audiolist.setAdapter(mCursorAdapter);
}
} //===========> "}" added
} //===========> "}" added