How do I pass data from sqlite database to another activity? - android

I have a database with for Columns {id,eng,kurd,ar} and I have populated a listview from it that shows only {eng} from the databse. I want to pass the {eng,kurd,ar} which have the same {id} when the user clicks an item in the listview, but when I click an item my app crashes, but everything else works fine there is no error in non of the other classes[adapter,sqliteopenhelper]
MainActivity.class
package com.rawa.rawadict;
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
Adapter adapter;
ArrayList<Item> myList = new ArrayList<Item>();
ListView myListView;
Databasehelper myDbHelper = new Databasehelper(this);
String engRes,kurdRes,arRes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
myDbHelper.createDatabase();
myDbHelper.openDatabase();
} catch (IOException e) {
throw new Error("Unable to create database");
}
Cursor cursor = myDbHelper.QueryData("select * from zankodict");
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
Item itemm = new Item();
itemm.setId(cursor.getString(0));
itemm.setEng(cursor.getString(1));
myList.add(itemm);
} while (cursor.moveToNext());
}
}
adapter = new Adapter(this, R.layout.single_row, myList);
myListView = (ListView) findViewById(R.id.lView);
myListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView text_id = (TextView) view.findViewById(R.id.tid);
String sel_id = text_id.getText().toString();
Cursor cursor = myDbHelper.QueryData("SELECT * FROM zankodict WHERE id =" + sel_id);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
engRes = cursor.getString(1);
kurdRes=cursor.getString(2);
arRes= cursor.getString(3);
} while (cursor.moveToNext());
}
}
// create intent to start another activity
Intent intent = new Intent(MainActivity.this, Result.class);
// add the selected text item to our intent.
Bundle extras = new Bundle();
extras.putString("eng",engRes);
extras.putString("kurd",kurdRes);
extras.putString("ar",arRes);
intent.putExtras(extras);
startActivity(intent);
}
}) ;
}
}
Result.class
package com.rawa.rawadict;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import java.io.IOException;
import java.util.ArrayList;
public class Result extends AppCompatActivity {
TextView etView2,ktView2,atView2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_view);
etView2 = (TextView) findViewById(R.id.etextView2);
ktView2 = (TextView) findViewById(R.id.ktextView2);
atView2 = (TextView) findViewById(R.id.atextView2);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String enG = extras.getString("eng");
String kurD = extras.getString("kurd");
String aR = extras.getString("ar");
etView2.setText(enG);
etView2.setText(kurD);
etView2.setText(aR);
}
}
I want to pass the Bundle to Result.class

The best approach to passing data from activity to activity and particularly from your database is to pass an (id) as an intent extra then when you arrive at the destination activity, extract it and use it to query your database based on that id.
This will reduce the amount of data you will have to pass through your intent instance.
If you only want to pass 3 items however, you can use intent extras instead of a Bundle like this:
Intent intent = new Intent(MainActivity.this, Result.class);
intent.putExtra("eng",engRes);
intent.putExtra"kurd",kurdRes);
intent.putExtra("ar",arRes);
startActivity(intent);
To extract this in your Results activity;
Intent intent = getIntent();
String enG = intent.getExtras().getString("eng");
String kurD = intent.getExtras().getString("kurd");
String aR = intent.getExtras().getString("ar");
I hope this helps and good luck!

Related

NumberFormatException invalid int

this is my saveddata.java page who can I solve
when I want to update data its say number expectation
and data insert but not update
I am trying to take the input values from EditText and I want to save it to SQLite Database. I don't know how to use the logcat [also please explain how can I read the errors from the LogCat].
package com.turningpoint.currencycounter;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class saveddata extends Activity{
DBHelper mydb;
private ListView obj;
ListViewAdapter lviewAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.saveditem);
ListViewAdapter arrayAdapter;
mydb = new DBHelper(this);
List<String> friendsnames= mydb.getAllCotacts();
List<String> friendsnames2= mydb.getAllCotacts2();
String frnames[]=friendsnames.toArray(new String[friendsnames.size()]);
String frnames2[]=friendsnames2.toArray(new String[friendsnames2.size()]);
arrayAdapter = new ListViewAdapter(this, frnames, frnames2);
obj = (ListView)findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
obj.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
// TODO Auto-generated method stub
int id_To_Search = arg2;
List array_list = mydb.getAllCotacts();
String s = array_list.get(id_To_Search).toString();
Cursor c2 = mydb.getData4(s);
while (c2.moveToNext()) {
String id = c2.getString(0);
String code = c2.getString(1);
// String code ..give me Number inut Expetation
int id2 = Integer.parseInt(id);
int code2 = Integer.parseInt(code);
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", id2);
int update=1;
dataBundle.putInt("update", update);
dataBundle.putInt("code", code2);
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
intent.putExtras(dataBundle);
Toast.makeText(getApplicationContext(), code, Toast.LENGTH_SHORT).show();
startActivity(intent);
}
Toast.makeText(getApplicationContext(), s,Toast.LENGTH_SHORT).show();
}
});
}
}
Use android:inputType="number" in EditText to make sure that the input is a number not a string or a charater like this
<EditText
.
.
.
android:inputType="number"
/>
Another solution:
Check if it is a number programmatically
boolean digitsOnly = TextUtils.isDigitsOnly(editText.getText());
Read this article. You will know how to use the logcat
https://guides.codepath.com/android/Debugging-Exceptions-within-your-App
I solve this problem
int code2 = Integer.parseInt(code);
this c2.getString(1) could not Int its give me String

How to retrieve single data in a list view in android

I am using built in list view to display data from the database in a list format,which displays name and contact number in the same line.I want to modify the names or numbers .So how can I get both name and number separately in a custom list view and displayed in some other text fields.
I tried using onTouchListener but this returns both the name and the number.
My code to display name and contact number as a list :
package com.example.hp.panic;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class Modify extends Activity {
SQLiteDatabase database;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_modify);
try {
database = openOrCreateDatabase("myDB", Context.MODE_PRIVATE,
null);
listView = (ListView) findViewById(R.id.contact_list);
ArrayList<String> arrayList = new ArrayList<>();
Cursor c = database.rawQuery("SELECT * FROM contacts ", null);
if (c.getCount() > 0) {
while (c.moveToNext()) {
String data = c.getString(0) + " " + c.getString(1);
arrayList.add(data);
ListAdapter listAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, arrayList);
listView.setAdapter(listAdapter);
}
} else {
Toast.makeText(Modify.this, "Table Empty",
Toast.LENGTH_SHORT).show();
}
c.close();
listView.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View
view,int i, long l) {
switch (i) {
case 0: {
}
break;
case 1: {
//Intent intent = new
// Intent(Modify.this,Modify2.class);
//startActivity(intent);
}
break;
case 2: {
//Intent intent = new
//Intent(Modify.this,Modify2.class);
//startActivity(intent);
}
break;
case 3: {
//Intent intent = new Intent(Modify.this,
//Modify2.class);
//startActivity(intent);
}
break;
case 4: {
/* Intent intent = new Intent(Modify.this,
Modify2.class);
startActivity(intent);*/
}
break;
}
}
});
} catch (Exception e) {
Log.d("Error", String.valueOf(e));
}
}
}

onClickListener doesnt work in second activity

I got an activity that is called from main activity. In the activity, i got database connections established and i fill a spinner according to db data. When a user selects one of the spinner items and press the button, the activity finishes and returns a value to the main activity (activity on result). But the button in the activity doesnt work, so the activity never returns a value to main activity. Here is the code:
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
public class mySpinnerClass extends Activity implements
OnItemSelectedListener {
private VeriTabani veritabani;
private SQLiteDatabase db;
Spinner spinner;
Button btnAdd;
String dataBaseName;
int selectedValue;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinner);
dataBaseName = "";
selectedValue = -1;
Intent i = getIntent();
dataBaseName = i.getStringExtra("dataBaseName");
veritabani = new VeriTabani(this);
db = veritabani.getWritableDatabase();
// Spinner element
spinner = (Spinner) findViewById(R.id.mySpinner);
// add button
btnAdd = (Button) findViewById(R.id.addButton);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
// Loading spinner data from database
loadSpinnerData();
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
if (dataBaseName == "phoneOrientation") {
Intent intent = getIntent();
intent.putExtra("phoneOrientation", selectedValue);
setResult(RESULT_OK, intent);
finish();
}
else if(dataBaseName== "phonePosition") {
Intent intent = getIntent();
intent.putExtra("phonePosition", selectedValue);
setResult(RESULT_OK, intent);
finish();
}
else if(dataBaseName =="Label"){
Intent intent=getIntent();
intent.putExtra("label",selectedValue);
setResult(RESULT_OK, intent);
finish();
}
}
});
}
private void loadSpinnerData() {
// Spinner Drop down elements
List<String> lables = getAllLabels();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
}
public List<String> getAllLabels() {
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + dataBaseName;
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(cursor.getColumnIndex("isim")));
} while (cursor.moveToNext());
}
// closing connection
// returning lables
return labels;
}
public int returnID(String item) {
int toBereturnedID;
Cursor myCursor = db.rawQuery("SELECT _id from " +dataBaseName+ " WHERE isim="+"'"+item+"'", null);
myCursor.moveToFirst();
toBereturnedID = myCursor.getInt(0);
return toBereturnedID;
}
public void onItemSelected(AdapterView<?> parent, View arg1, int position, long arg3) {
// TODO Auto-generated method stub
String label = parent.getItemAtPosition(position).toString();
selectedValue = returnID(label);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
You are calling loadSpinnerData(); method in onCreate() of activity so dataBaseName is always going to be empty, so you want to have value of spinner at time click you need to call that with on onClick() method of button, which will give you correct dataBaseName and use dataBaseName.equals("phoneOrientation") instead of dataBaseName == "phoneOrientation"
Try creating a new Intent instead of getIntent().
Intent intent=new Intent();
intent.putExtra("label",selectedValue);
setResult(RESULT_OK, intent);
finish();
Hope it helps.

How to do switch case statement to display ListView in Android

I newbie in this field.
my application have 6 buttons with different category. when i click on one of the button it will go to another page for displaying listView for particular category in my database.
my problem is, I don't know how do switch case for this method.
Log.d("Reading", "Reading all Kategori ..");
List<UkmLocation> kategori = db.getCategoryFaculty();
for(UkmLocation k : kategori) {
results.add(k.getName());
results_id.add(k.getID());
}
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.textView1,results);
setListAdapter(adapter);
I want to include getCategoryHall, getCategoryFacilty,and getCategoryAdmin in this QSFacultyLocation.java. so that, i no need to create another activity merely to get getCategoryHall, getCategoryFacilty,and getCategoryAdmin (listView).Because it just using same coding.
below is my full code for:
QSFacultyLocation.java
package com.example.ukmlocationsearching;
import java.util.ArrayList;
import java.util.List;
import com.example.ukmlocationsearching.R;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class QSFacultyLocation extends ListActivity {
//------------------------------------------------------------------
// Declaration
public static UkmLocation selectedPOI = null;
final DatabaseHandler db = new DatabaseHandler(this);
private EditText filterText = null;
ArrayAdapter<String> adapter = null;
final ArrayList<String> results = new ArrayList<String>();
final ArrayList<String> results_id = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.qs_faculty_location);
final Intent c = new Intent(QSFacultyLocation.this, QSLocationDetail.class);
//------------------------------------------------------------------
// Link editText to layout item
filterText = (EditText) findViewById(R.id.search_box);
filterText.addTextChangedListener(filterTextWatcher);
//------------------------------------------------------------------
// Reading Poi
/*SearchKategori searchKategori = new SearchKategori();
UkmLocation selectedKategori = searchKategori.getSelectedKategori();
List<UkmLocation> locationList = null;*/
Log.d("Reading", "Reading all Kategori ..");
List<UkmLocation> kategori = db.getCategoryFaculty();
//------------------------------------------------------------------
// Determine list POI with category
for(UkmLocation k : kategori) {
results.add(k.getName());
results_id.add(k.getID());
}
//------------------------------------------------------------------
// Set list arrayAdapter to adapter
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.textView1,results);
setListAdapter(adapter);
//------------------------------------------------------------------
// Set ListView from ListActivity
ListView lv = getListView();
lv.setTextFilterEnabled(true);
//------------------------------------------------------------------
// Set click event from listView
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
Log.d("test", "position:" + position);
Log.d("test", "actualname:" + db.getUkmLocationByName(adapter.getItem(position)).getName());
// String poiID = results_id.get(position);
String poiID = db.getUkmLocationByName(adapter.getItem(position)).getID();
setSelectedPoi(poiID);
startActivity(c);
}
});
//------------------------------------------------------------------
// Closing db (if any)
// db.close();
}
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter.getFilter().filter(s);
}
};
#Override
protected void onDestroy() {
super.onDestroy();
filterText.removeTextChangedListener(filterTextWatcher);
}
public UkmLocation getSelectedPoi() {
return selectedPOI;
}
public void setSelectedPoi(String poiID) {
selectedPOI = db.getUkmLocation(poiID);
Log.d("test2", "_id:" + db.getUkmLocation(poiID).getID());
Log.d("test2", "Name:" + db.getUkmLocation(poiID).getName());
// Closing db
db.close();
}
}
QuickSearchMenu.java
package com.example.ukmlocationsearching;
import java.io.IOException;
import com.example.ukmlocationsearching.R;
import com.example.ukmlocationsearching.R.id;
import com.example.ukmlocationsearching.R.layout;
import com.example.ukmlocationsearching.R.menu;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.SQLException;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class QuickSearchMenu extends Activity implements OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
//---------------------------------------------------------------------------
// Initiate database data
initiateDb();
//---------------------------------------------------------------------------
super.onCreate(savedInstanceState);
setContentView(R.layout.quick_search_menu);
View faculty = findViewById(R.id.button2);
faculty.setOnClickListener(this);
View researchInstitute = findViewById(R.id.button1);
researchInstitute.setOnClickListener(this);
View college = findViewById(R.id.button3);
college.setOnClickListener(this);
View admin = findViewById(R.id.button4);
admin.setOnClickListener(this);
View facility = findViewById(R.id.button5);
facility.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.quick_search_menu, menu);
return true;
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button1:
Intent b1 = new Intent(this, QSResearch.class);
startActivity(b1);
break;
case R.id.button2:
Intent b2 = new Intent(this,QSFacultyLocation.class);
startActivity(b2);
break;
/*case R.id.button3:
Intent b3 = new Intent(this,QuickSearchCollege.class);
startActivity(b3);
break;
case R.id.button4:
Intent b4 = new Intent(this,QuickSearchFaculty.class);
startActivity(b4);
break;
case R.id.button5:
Intent b5 = new Intent(this,QuickSearchCollege.class);
startActivity(b5);
break;*/
}
}
//---------------------------------------------------------------------------
// Initiate database data
public void initiateDb() {
DatabaseHandler myDbHandler = new DatabaseHandler(this);
try {
myDbHandler.createDataBase();
}
catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHandler.openDataBase();
}
catch(SQLException sqle) {
throw sqle;
}
Log.d("Initiate", "UKM Location Count: " + myDbHandler.getUkmLocationCount());
/*Log.d("Initiate", "Kategori Count: " + myDbHandler.getKategoriCount());
Log.d("Initiate", "KategoriPoi Count: " + myDbHandler.getKategoriPoiCount());*/
myDbHandler.close();
}
//------------------------------------------------------------------------------
}
please do help me solve this. thank you
First,pass a query or simply any key value such as department id or department name as an intent with each button click using
intentname.putExtra(keyname_used_to_retrieve_value,value_to_be_passed_to_next_activity);
case R.id.button1:
String query="select * from table_name where something='xyz'";
Intent b1 = new Intent(this, QSResearch.class);
b1.putExtra("myextrakey",query);
startActivity(b1);
Then, receive the intent in the onCreate method of list activity as follows,initialise database and call user defined mylist() and setuplist() functions
Intent i=getIntent();
String x=i.getStringExtra("myextrakey");//this assigns the query to string x
//open database here
mylist();//call myList function which i have defined in the following lines
setUpList();//call setUpList function which i have defined in the following lines
This is the myList function:
private void myList() {
myownlist= new ArrayList<String>();
Cursor myCursor = database.rawQuery(x,null);
myCursor.moveToFirst();
if(!myCursor.isAfterLast()) {
do {
//selects data in column 2 to be displayed on list
String listitem= myCursor.getString(2);
myownlist.add(listitem);
} while (myCursor.moveToNext());
}
myCursor.close();
}
This is the setUpList() function:
private void setUpList() {
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, myownlist));
ListView lv = getListView();
}

Retrieving contacts in list view and displaying the name and phone number in next activity with click action

I have got the code where through content provider i am retrieving the phone contacts and displaying them in list format.
I want to display the phone no and name of the particular person in next activity when i click on the list format contacts from first activity. I am getting errors in this its not able to perform click operation and display it on to next activity Please help me with this.
Here is the first Activity through i am display the contacts through content provider.
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
public class MsatActivity extends ListActivity
{
TextView ContactsTV;
ListView lv;
Cursor c;
public static final Uri CONTENT_URI =
Uri.parse("content://com.android.contacts/contacts/1557");
public void onListItemClick(View v)
{
Intent outData = new Intent(this,Full.class);
// setResult(Activity.RESULT_OK, outData);
startActivity(outData);
}
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Uri myContacts = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
c = getContentResolver().query(myContacts, new String[]
{ContactsContract.CommonDataKinds.Phone._ID,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER}
, null, null, null);
String[] columns = new String[]
{
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER};
int[] to = new int[] {R.id.text1,R.id.text2};
SimpleCursorAdapter mAdapter = new
SimpleCursorAdapter(this,R.layout.listitems, c, columns, to);
setListAdapter(mAdapter);
lv.setOnItemSelectedListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int pos, long id)
{
int rowId = c.getInt(c.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone._ID));
Uri outURI = Uri.parse(CONTENT_URI.toString() + "/" + rowId);
Intent outData = new Intent();
outData.setData(outURI);
setResult(Activity.RESULT_OK, outData);
finish();
}
});
}
}
Here is the second activity.......
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.Button;
public class Full extends Activity
{
private static final int CONTACT_PICKER_RESULT = 1001;
String name;
Cursor cursor;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
Button getContacts = (Button)findViewById(R.id.button1);
getContacts.setOnItemClickListener(new View.OnItemClickListener()
{
public void onClick(View v)
{
Intent i = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(i, CONTACT_PICKER_RESULT);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK)
{
switch (requestCode)
{
case CONTACT_PICKER_RESULT:
try {
Uri result = data.getData();
String id = result.getLastPathSegment();
//Get Name
cursor = getContentResolver().query(result, null, null, null, null);
if (cursor.moveToFirst())
{
name =
cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
}
}
catch (Exception e)
{
}
}
}
}
}
I really can't figure out your code at all. The first activity seems to be creating an Intent to start the Full Activity, but it has two "onclick" methods and it does a setResult() and finish() even though it never did getIntent()!
The second activity creates an ACTION_PICK Intent for the entire Phone table, and handles the return by doing a query on the result, which should be the contact ID of the contact whose # the user picked. I don't think it's the entire URI, though; you should verify that through debug. You then try to get the DISPLAY_NAME for this contact.
Fine, but I don't see why you need the first Activity at all.
I posted some instructions on using the Contacts Provider somewhere else on Stackoverflow; just search for android and ContactsContract.

Categories

Resources