Showing contact from the contact loader Manager - contacts

I am showing the contact list from the contact table but not able to get the phone number using the same on RecyclerView.My code is -
package com.oodles.oodlesapprtc;
import android.annotation.SuppressLint;
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.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import java.util.ArrayList;
/**
* Created by ankita on 13/4/17.
*/
public class LoginUserActivity extends AppCompatActivity {
public static final int CONTACT_LOADER_ID = 78;
RecyclerView loginUserRecycler;
ArrayList<ContactBeans> contactBeanses;
String sortOrder = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME +
" COLLATE LOCALIZED ASC";
private static final String[] PROJECTION2 = {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY, ContactsContract.Contacts.PHOTO_URI,ContactsContract.Contacts.HAS_PHONE_NUMBER
};
private static final String[] PROJECTION3 = {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY, ContactsContract.Contacts.PHOTO_URI, ContactsContract.Contacts.LOOKUP_KEY
};
private static final String[] PROJECTION = {
ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY, ContactsContract.CommonDataKinds.Phone.NUMBER
};
// private static final String[] PROJECTION1 = {
// ContactsContract.Data.CONTACT_ID, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY,
// ContactsContract.CommonDataKinds.Phone.NUMBER
// };
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_user_activity);
initViews();
}
private void initViews() {
getLoaderManager().initLoader(0, null, contactLoaderManager);
initRecycler();
}
private void initRecycler() {
loginUserRecycler = (RecyclerView) findViewById(R.id.loginUserRecycler);
loginUserRecycler.setLayoutManager(new LinearLayoutManager(this));
loginUserRecycler.setItemAnimator(new DefaultItemAnimator());
}
LoaderManager.LoaderCallbacks<Cursor> contactLoaderManager = new LoaderManager.LoaderCallbacks<Cursor>() {
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// String[] projectionFields = new String[]{ContactsContract.Contacts._ID,
// ContactsContract.Contacts.DISPLAY_NAME,ContactsContract.PhoneLookup.NORMALIZED_NUMBER,
// ContactsContract.Contacts.PHOTO_URI};
// Construct the loader
// Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
// ContactsContract.Contacts.CONTENT_URI
// Uri lookupUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
// Uri.encode(phoneNumber));
CursorLoader cursorLoader = new CursorLoader(LoginUserActivity.this,
ContactsContract.Contacts.CONTENT_URI, // URI
PROJECTION2, // projection fields
null, // the selection criteria
null, // the selection args
sortOrder // the sort order
);
return cursorLoader;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
loginUserRecycler.setAdapter(new CursorRecyclerAdapter(LoginUserActivity.this, data));
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}
};
}
My Adapter is -
package com.oodles.oodlesapprtc;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by ankita on 13/4/17.
*/
public class CursorRecyclerAdapter extends RecyclerView.Adapter<ContactViewHolder> {
private Cursor mCursor;
private final int mNameColIdx,
mIdColIdx;
int phoneNumber;
int hasPhoneNumber;
private Context mContext;
public CursorRecyclerAdapter(Context context, Cursor cursor) {
mCursor = cursor;
this.mContext = context;
mNameColIdx = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME_PRIMARY);
mIdColIdx = cursor.getColumnIndex(ContactsContract.Contacts._ID);
hasPhoneNumber = cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
}
#Override
public ContactViewHolder onCreateViewHolder(ViewGroup parent, int pos) {
View listItemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.contact_row, parent, false);
return new ContactViewHolder(listItemView);
}
#Override
public void onBindViewHolder(ContactViewHolder contactViewHolder, int pos) {
mCursor.moveToPosition(pos);
String contactName = mCursor.getString(mNameColIdx);
long contactId = mCursor.getLong(mIdColIdx);
Contact c = new Contact();
Log.e("ddhdhdhhdhdhdhd",hasPhoneNumber+"");
c.name = contactName;
c.number = getPhoneNumberFromContactId(contactId);
c.profilePic = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
getPhoneNumberFromContactId(contactId);
contactViewHolder.bind(c);
}
private String getPhoneNumberFromContactId(long contactId) {
String contactNumber = "8874675724";
return contactNumber;
}
#Override
public int getItemCount() {
return mCursor.getCount();
}
}
How can I get the phone number for the same i am getting a cursorindexoutofbound exception and has phone number value as 3 but it can be only 0 or 1 why it is 3 i don't understand this.
Can Anyone please explain this to me also please explain how the contact fetch works

You have a few issues in the code:
You're querying on the Contacts table, but sorting using a CommonDataKinds.Phone table field, that's not good, you can sort using Contacts.DISPLAY_NAME_PRIMARY instead.
cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER) gives you a column index, not the value of the field, that's why you're getting 3 (it's the 4rd field defined in PROJECTION2), change hasPhoneNumber to mHasPhoneNumberIdx to avoid confusion.
add hasPhoneNumber = mCursor.getInt(mHasPhoneNumberIdx); to your onBindViewHolder method, to get the actual value.
Running a long command like a real implementation of getPhoneNumberFromContactId within onBindViewHolder is really bad... you should change your main query so you do two big queries, one for all contacts, one for all phones, and then use some HashMap to get a phone using a contact-id.

Related

Use Datawedge with flutter

I am trying to use the datawedge intent API with my flutter application, on a Zebra android scanner. I started to use the Zebra EMDK API from a git repository, which works perfectly. Now I want to migrate it (which is recommended by Zebra) because I want it to be also available on mobiles (if it is possible).
I am trying to follow the instructions from this page and merge it with the code from the git repo, but no scan event is detected in my app.
Has someone already done this and could help me?
Here is my MainActivity.java:
package com.example.test_datawedge;
import android.os.Bundle;
import io.flutter.app.FlutterActivity;
import io.flutter.plugins.GeneratedPluginRegistrant;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
// import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.EventChannel.EventSink;
import io.flutter.plugin.common.EventChannel.StreamHandler;
import io.flutter.plugins.GeneratedPluginRegistrant;
import java.util.ArrayList;
public class MainActivity extends FlutterActivity {
private static final String BARCODE_RECEIVED_CHANNEL = "samples.flutter.io/barcodereceived";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
// setContentView(R.layout.activity_main);
IntentFilter filter = new IntentFilter();
filter.addCategory(Intent.CATEGORY_DEFAULT);
filter.addAction(getResources().getString(R.string.activity_intent_filter_action));
// registerReceiver(myBroadcastReceiver, filter);
new EventChannel(getFlutterView(), BARCODE_RECEIVED_CHANNEL).setStreamHandler(
new StreamHandler() {
private BroadcastReceiver barcodeBroadcastReceiver;
#Override
public void onListen(Object arguments, EventSink events) {
Log.d("FLUTTERDEMO", "EventChannelOnListen");
barcodeBroadcastReceiver = createBarcodeBroadcastReceiver(events);
registerReceiver(
barcodeBroadcastReceiver, new IntentFilter("readBarcode"));
}
#Override
public void onCancel(Object arguments) {
Log.d("FLUTTERDEMO", "EventChannelOnCancel");
unregisterReceiver(barcodeBroadcastReceiver);
barcodeBroadcastReceiver = null;
}
}
);
}
// #Override
// protected void onDestroy()
// {
// super.onDestroy();
// unregisterReceiver(myBroadcastReceiver);
// }
//
// After registering the broadcast receiver, the next step (below) is to define it.
// Here it's done in the MainActivity.java, but also can be handled by a separate class.
// The logic of extracting the scanned data and displaying it on the screen
// is executed in its own method (later in the code). Note the use of the
// extra keys are defined in the strings.xml file.
//
private BroadcastReceiver createBarcodeBroadcastReceiver(final EventSink events) {
return new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.d("FLUTTERDEMO", "createBarcodeBroadcastReceiver " + action);
if(action.equals("readBarcode")){
String barcode = intent.getStringExtra("barcode");
String barcodetype = intent.getStringExtra("barcodetype");
Log.d("FLUTTERDEMO", "createBarcodeBroadcastReceiver " + barcode);
events.success(barcode);
}
}
};
}
//
// The section below assumes that a UI exists in which to place the data. A production
// application would be driving much of the behavior following a scan.
//
// private void displayScanResult(Intent initiatingIntent, String howDataReceived)
// {
// String decodedSource = initiatingIntent.getStringExtra(getResources().getString(R.string.datawedge_intent_key_source));
// String decodedData = initiatingIntent.getStringExtra(getResources().getString(R.string.datawedge_intent_key_data));
// String decodedLabelType = initiatingIntent.getStringExtra(getResources().getString(R.string.datawedge_intent_key_label_type));
// final TextView lblScanSource = (TextView) findViewById(R.id.lblScanSource);
// final TextView lblScanData = (TextView) findViewById(R.id.lblScanData);
// final TextView lblScanLabelType = (TextView) findViewById(R.id.lblScanDecoder);
// lblScanSource.setText(decodedSource + " " + howDataReceived);
// lblScanData.setText(decodedData);
// lblScanLabelType.setText(decodedLabelType);
// }
}
Zebra EMDK retrieves data by overriding the 'onStatus' and 'onData' functions.
Retrieve your barcode data from 'onData'

Android ActionBar error

package mavilla.paavaiinstitutions;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.ActionBar;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class MainActivity extends Activity {
int mPosition = -1;
String mTitle = "";
// Array of strings storing country names
String[] mCountries ;
// Array of integers points to images stored in /res/drawable-ldpi/
int[] mFlags = new int[]{
R.drawable.home,
R.drawable.about,
R.drawable.ins,
R.drawable.campus,
R.drawable.compass,
R.drawable.gallery,
R.drawable.cap,
R.drawable.alumini,
R.drawable.tieup,
R.drawable.contact
};
// Array of strings to initial counts
String[] mCount = new String[]{
"", "", "", "", "",
"", "", "", "", "" };
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private LinearLayout mDrawer ;
private List<HashMap<String,String>> mList ;
private SimpleAdapter mAdapter;
final private String COUNTRY = "country";
final private String FLAG = "flag";
final private String COUNT = "count";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Getting an array of country names
mCountries = getResources().getStringArray(R.array.countries);
// Title of the activity
mTitle = (String)getTitle();
// Getting a reference to the drawer listview
mDrawerList = (ListView) findViewById(R.id.drawer_list);
// Getting a reference to the sidebar drawer ( Title + ListView )
mDrawer = ( LinearLayout) findViewById(R.id.drawer);
// Each row in the list stores country name, count and flag
mList = new ArrayList<HashMap<String,String>>();
for(int i=0;i<10;i++){
HashMap<String, String> hm = new HashMap<String,String>();
hm.put(COUNTRY, mCountries[i]);
hm.put(COUNT, mCount[i]);
hm.put(FLAG, Integer.toString(mFlags[i]) );
mList.add(hm);
}
// Keys used in Hashmap
String[] from = { FLAG,COUNTRY,COUNT };
// Ids of views in listview_layout
int[] to = { R.id.flag , R.id.country , R.id.count};
// Instantiating an adapter to store each items
// R.layout.drawer_layout defines the layout of each item
mAdapter = new SimpleAdapter(this, mList, R.layout.drawer_layout, from, to);
// Getting reference to DrawerLayout
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
// Creating a ToggleButton for NavigationDrawer with drawer event listener
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer , R.string.drawer_open,R.string.drawer_close){
/** Called when drawer is closed */
public void onDrawerClosed(View view) {
highlightSelectedCountry();
supportInvalidateOptionsMenu();
}
/** Called when a drawer is opened */
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle("Select a Country");
supportInvalidateOptionsMenu();
}
};
// Setting event listener for the drawer
mDrawerLayout.setDrawerListener(mDrawerToggle);
// ItemClick event handler for the drawer items
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// Increment hit count of the drawer list item
incrementHitCount(position);
if(position < 5) { // Show fragment for countries : 0 to 4
showFragment(position);
}else{ // Show message box for countries : 5 to 9
Toast.makeText(getApplicationContext(), mCountries[position], Toast.LENGTH_LONG).show();
}
// Closing the drawer
mDrawerLayout.closeDrawer(mDrawer);
}
});
// Enabling Up navigation
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
// Setting the adapter to the listView
mDrawerList.setAdapter(mAdapter);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
public void incrementHitCount(int position){
HashMap<String, String> item = mList.get(position);
String count = item.get(COUNT);
item.remove(COUNT);
if(count.equals("")){
count = " 1 ";
}else{
int cnt = Integer.parseInt(count.trim());
cnt ++;
count = " " + cnt + " ";
}
item.put(COUNT, count);
mAdapter.notifyDataSetChanged();
}
public void showFragment(int position){
//Currently selected country
mTitle = mCountries[position];
// Creating a fragment object
CountryFragment cFragment = new CountryFragment();
// Creating a Bundle object
Bundle data = new Bundle();
// Setting the index of the currently selected item of mDrawerList
data.putInt("position", position);
// Setting the position to the fragment
cFragment.setArguments(data);
// Getting reference to the FragmentManager
FragmentManager fragmentManager = getSupportFragmentManager();
// Creating a fragment transaction
FragmentTransaction ft = fragmentManager.beginTransaction();
// Adding a fragment to the fragment transaction
ft.replace(R.id.content_frame, cFragment);
// Committing the transaction
ft.commit();
}
// Highlight the selected country : 0 to 4
public void highlightSelectedCountry(){
int selectedItem = mDrawerList.getCheckedItemPosition();
if(selectedItem > 4)
mDrawerList.setItemChecked(mPosition, true);
else
mPosition = selectedItem;
if(mPosition!=-1)
getSupportActionBar().setTitle(mCountries[mPosition]);
}
}
i have extended Main Activity from Activity as shown to apply custom theme.
But I'm getting error below in actionBar code:
getSupportActionBar()
// Enabling Up navigation
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
Please help me as i am very new in stackoverflow and android..thanks in advance.
You are no longer using the support ActionBarActivity, but the normal Android Activity.
Thats why instead of
getSupportActionBar() you have to call getActionBar()
supportInvalidateOptionsMenu() you have to call invalidateOptionsMenu()
getSupportFragmentManager() you have to call getFragmentManager()
and so on..

The operator - under defined for the arguement type(s) EditText, int

Im trying to create an activity which adds name, age, and maxhr to sqlite and will be displayed in a listview in Eclipse. name and age is an input text. Maxhr is age(input text) minus 220. But im getting "The operator - under defined for the arguement type(s) EditText, int" error. I can't seem to find the answer for this error. Does anyone know how to fix it?
package com.heartrate.monitoring.activities;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.heartratemonitoringapp.R;
import com.heartrate.monitoring.dao.UserDAO;
import com.heartrate.monitoring.model.User;
public class AddUserActivity extends Activity implements OnClickListener {
public static final String TAG = "AddUserActivity";
private EditText mTxtName;
private EditText mTxtAge;
private Button mBtnAdd;
private UserDAO mUserDao;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_user);
getActionBar().setDisplayHomeAsUpEnabled(true);
initViews();
this.mUserDao = new UserDAO(this);
}
private void initViews() {
this.mTxtName = (EditText) findViewById(R.id.txt_name);
this.mTxtAge = (EditText) findViewById(R.id.txt_age);
this.mBtnAdd = (Button) findViewById(R.id.btn_add);
this.mBtnAdd.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_add:
Editable name = mTxtName.getText();
Editable age = mTxtAge.getText();
if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(age)){
// add the user to database
double mhr;
double maxhr;
mhr = Double.parseDouble(mTxtAge.getText().toString());;
maxhr = mhr - 220;
User createdUser = mUserDao.createUser(
name.toString(), age.toString(),
maxhr.toString());
Log.d(TAG, "added user : "+ createdUser.getName());
Intent intent = new Intent();
intent.putExtra(ListUserActivity.EXTRA_ADDED_USER, createdUser);
setResult(RESULT_OK, intent);
Toast.makeText(this, R.string.user_created_successfully, Toast.LENGTH_LONG).show();
finish();
}
else {
Toast.makeText(this, R.string.empty_fields_message, Toast.LENGTH_LONG).show();
}
break;
default:
break;
}
}
#Override
protected void onDestroy() {
super.onDestroy();
mUserDao.close();
}
}
Remove the extra ; on this line: mhr = Double.parseDouble(mTxtAge.getText().toString());;

Not able to store value getting from Transliteration using GWT

I am new to GWT and I want to make a application in which words are transliterate and store in a varible.which can be used for storing values in database.
But when I am trying to store in variable it gives null value when am printing it.
package com.google.gwt.language.sample.hellolanguage.client;
import java.util.ArrayList;
import java.util.List;
import com.google.gwt.language.client.transliteration.LanguageCode;
import com.google.gwt.language.client.transliteration.SupportedDestinationLanguages;
import com.google.gwt.language.client.transliteration.control.TransliterationControl;
import com.google.gwt.language.client.transliteration.control.TransliterationControlOptions;
import com.google.gwt.language.client.transliteration.text.Transliteration;
import com.google.gwt.language.client.transliteration.text.TransliterationCallback;
import com.google.gwt.language.client.transliteration.text.TransliterationResult;
import com.google.gwt.user.client.ui.Composite;
public class Trans extends Composite {
ArrayList<String> wordsArray= new ArrayList<String>();
public String sss;
public void recieve(String ss)
{
this.sss=ss;
System.out.println(sss);
}
public String send(){
return sss;
}
public Trans(ArrayList<String> str) {
initTransliterationControls(str);
//Here I want to print
System.out.println(sss);
}
public void initTransliterationControls(ArrayList<String> wordsArray1) {
//ArrayList<String> wordsArray= new ArrayList<String>();
// wordsArray=wordsArray1;
//System.out.println(wordsArray1.size());
// for(int i=0;i<wordsArray1.size();i++)
//{
//wordsArray.add(wordsArray1.get(i).toString());
//}
wordsArray.add(wordsArray1.get(0).toString());
wordsArray.add("Rerrebok");
wordsArray.add("Woodland j_74_Hi-gh Heels Boots");
//System.out.println(wordsArray);
Transliteration.transliterate(wordsArray, LanguageCode.ENGLISH,
LanguageCode.HINDI, new TransliterationCallback() {
#Override
public void onCallback(TransliterationResult result) {
// System.out.println(result.getTransliterations().toString());
List<List<String>> collection= new ArrayList<List<String>>();
collection=result.getTransliterations();
// Here I am storing it on sss but when I am print outside this function it gives Null
sss=collection.get(0).get(0).toString();
}
});
}
}

Search in ListView android

I'm using the following class to so search in listView of countries
package com.androidhive.androidlistviewwithsearch;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.inputmethod.InputMethodManager;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class MainActivity extends Activity {
private ListView lv;
SimpleCursorAdapter cursorAdapter;
ArrayAdapter<String> adapter;
EditText inputSearch;
private SQLiteAdapter mySQLiteAdapter;
ArrayList<HashMap<String, String>> productList;
public static final String COUNTRY_NAME = "COUNTRY_NAME";
String[] countryName;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToWrite();
int isEmpty = mySQLiteAdapter.isEmpty();
if (isEmpty == 0) {
mySQLiteAdapter.insert("Afghanistan", "102", "119", "119");
mySQLiteAdapter.insert("Albania", "127", "128", "129");
mySQLiteAdapter.insert("Algeria", "14", "14", "17");
mySQLiteAdapter.insert("American Samoa", "911", "911", "911");
mySQLiteAdapter.insert("Andorra", "118", "118", "110");
mySQLiteAdapter.insert("Angola", "118", "118", "110");
mySQLiteAdapter.insert("Panama", "911", "911", "911");
mySQLiteAdapter.insert("Papua New Guinea /Port Moresby", "", "110", "000");
mySQLiteAdapter.insert("Yemen", "191", "191", "194");
mySQLiteAdapter.insert("Zambia", "991/112", "993/112", "999/112");
mySQLiteAdapter.insert("Zimbabwe", "994/999", "993/999", "995/999");
}
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToRead();
Cursor cursor = mySQLiteAdapter.queueAll();
startManagingCursor(cursor);
List<String> list = new ArrayList<String>();
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
String countries = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.COUNTRIES_CONTENT)).toString().trim();
System.out.println("countries: " + countries);
list.add(countries);
cursor.moveToNext();
}
}
countryName = new String[list.size()];
countryName = list.toArray(countryName);
mySQLiteAdapter.close();
lv = (ListView) findViewById(R.id.list_view);
inputSearch = (EditText) findViewById(R.id.inputSearch);
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name, countryName);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parentView, View childView, int position, long id) {
Intent intent ;
Bundle b = new Bundle();
b.putString(COUNTRY_NAME, countryName[position]);
intent = new Intent(getApplicationContext(), CountryNumbers.class);
intent.putExtras(b);
startActivity(intent);
finish();
}
});
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
MainActivity.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
}
this code works well and do a search and it also do the setOnItemClickListener that opens the Activity that contains info about the selected country.
But when I do search and I wrote "E" for example, I found the list changed and gets countries that starts with "E" but When I press for example the second country that gets from search, it opens the country with second index in "countryName" array.
How can I solve this issue and get the info of the selected country from the search?
Hope anyone got my mean.
Thanks in advance.
I solved it by replacing this line
b.putString(COUNTRY_NAME, countryName[position]);
by this line
b.putString(COUNTRY_NAME, adapter.getItem(position));