I am having trouble in running my Android app. It is a simple activity meant to get data from a remote database via HTTP.
I am getting these two errors in log cat:
Error parsing to json on getJarrayFromString();
org.json.JSONException: Value Database of type java.lang.String cannot
be converted to JSONArray.
And:
Error at fillproductlist(): java.lang.NullPointerException
I am not very good at Java/Android and this is first time I am asking this question here. I am unable to understand what layer of my app the problem might be in (my Java code, PHP, or database code)?
Code snapshot:
private void fillProductList() {
if (utils.isInternet()
&& CustomHttpClient.isAddressOk(Utils.LINK_PRODUCTS)) {
final int from = bid.size();
final int nr = 5;
long sqliteSize = db.size(mySqlDatabase.TABLE_BOOKS);
if (from == 0) {
// we add the post variables and values for the request
postParameters.add(new BasicNameValuePair("from", String
.valueOf(0).toString()));
postParameters.add(new BasicNameValuePair("nr", String.valueOf(
nr).toString()));
} else {
postParameters.add(new BasicNameValuePair("from", String
.valueOf(from).toString()));
postParameters.add(new BasicNameValuePair("nr", String.valueOf(
nr).toString()));
}
postParameters.add(new BasicNameValuePair("title", titleSearch));
postParameters.add(new BasicNameValuePair("code", codeSearch));
postParameters.add(new BasicNameValuePair("module", moduleSearch));
if (sortOrder != null)
postParameters.add(new BasicNameValuePair("order", sortOrder));
if (sortType != null)
postParameters.add(new BasicNameValuePair("by", sortType));
task = new RequestTask("books", postParameters);
task.setOnTaskCompleted(new OnTaskCompletedListener() {
public void onTaskStarted() {
if (!rlLoading.isShown()) {
rlLoading.startAnimation(fadeIn());
rlLoading.setVisibility(View.VISIBLE);
}
IS_PRODUCTS_TASK = true;
}
public void onTaskCompleted(String result) {
try {
if (result != "") {
// Enter the remote php link
// we convert the response into json array
jarray = utils.getJarrayFromString(result);
int mysqlSize = (jarray.getJSONObject(0)
.getInt("numRows"));
Log.i(DEBUG, "From " + from + " to " + mysqlSize);
if (from <= mysqlSize) {
int rows;
// we check to see if there is 0
if (jarray.length() > 0) {
Log.i(DEBUG,
"From "
+ from
+ " to "
+ Math.floor(mysqlSize / nr)
* nr);
if (from + 5 <= Math.floor(mysqlSize / nr)
* nr) {
rows = jarray.length();
} else {
rows = mysqlSize % nr + 1;
Utils.IS_ENDED_PRODUCT_LIST = true;
}
ArrayList<String> list = new ArrayList<String>();
for (int i = 1; i < rows; i++) {
JSONObject row = jarray
.getJSONObject(i);
bid.add(row.getInt("bid"));
bTitle.add(row.getString("bTitle"));
bCode.add(row.getString("bCode"));
bPrice.add(row.getString("bPrice")
+ "£");
bDescription.add(row
.getString("bDescription"));
bModule.add(row.getString("bModule"));
bImage.add(Utils.PATH
+ row.getString("bImage"));
list.add(row.getString("bImage"));
// we check if this id already exists in the db, if it doesn't exists w create new one
if (!db.hasIDbooks(row.getInt("bid")))
db.createRowOnBooks(
row.getInt("bid"),
row.getString("bTitle"),
row.getString("bCode"),
row.getString("bPrice"),
row.getString("bDescription"),
row.getString("bModule"),
Utils.PATH
+ row.getString("bImage"),
row.getString("bSpecialOffer"),
row.getInt("bSpecialDiscount"),
row.getString("bDateAdded"));
Log.i(DEBUG,
row.getString("bDescription"));
}
new DownloadImages(list, bAdapter)
.execute();
}
}
postParameters.removeAll(postParameters);
} else {
Utils.IS_ENDED_PRODUCT_LIST = true;
if (rlLoading.isShown()) {
rlLoading.startAnimation(fadeOut());
rlLoading.setVisibility(View.INVISIBLE);
}
}
} catch (Exception e) {
Log.e(DEBUG,
"Error at fillProductList(): " + e.toString());
}
}
});
task.execute();
} else {
// if we are not connected on internet or somehow the link would not work, then we will take the rows stored in sqlite db
if (db.size(mySqlDatabase.TABLE_BOOKS) > 0) {
Cursor cursor = db.getBookssRows(mySqlDatabase.TABLE_BOOKS);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
bid.add(cursor.getInt(cursor
.getColumnIndex(mySqlDatabase.KEY_BID)));
bTitle.add(cursor.getString(cursor
.getColumnIndex(mySqlDatabase.KEY_BTITLE)));
bCode.add(cursor.getString(cursor
.getColumnIndex(mySqlDatabase.KEY_BCODE)));
bPrice.add(cursor.getString(cursor
.getColumnIndex(mySqlDatabase.KEY_BPRICE)) + "£");
bDescription.add(cursor.getString(cursor
.getColumnIndex(mySqlDatabase.KEY_BDESCRIPTION)));
bModule.add(cursor.getString(cursor
.getColumnIndex(mySqlDatabase.KEY_BMODULE)));
bImage.add(cursor.getString(cursor
.getColumnIndex(mySqlDatabase.KEY_BIMAGE)));
cursor.moveToNext();
}
bAdapter.notifyDataSetChanged();
Utils.IS_ENDED_PRODUCT_LIST = true;
}
}
}
In the OnTaskCompleted before
jarray = utils.getJarrayFromString(result);
add a log entry with
Log.i(DEBUG,result);
I am suspecting that you are getting a null value as result
if(result!="")
does not ensure a valid value.
Cheers
Related
I'm getting -1 as the length of my JSON array. I'm using retrofit and GSON implementations. Below is the JSON that I'm receiving
`[{"info":"green"},[{"username":"abcd.abcd","coords":"-2.9089067,56.4395"}]]`
I managed to extract the "info" object but when it comes to the following array, I cannot extract the data due to its length.
Call < ResponseBody > call = uploadAPIs.responderList(0);
call.enqueue(new Callback < ResponseBody > () {
#Override
public void onResponse(Call < ResponseBody > call, Response < ResponseBody > response) {
String res;
boolean error = false;
if (!response.isSuccessful()) {
Log.d("Responders", "code: " + response.code());
} else {
try {
responders.clear();
res = response.body().string();
Log.d("Responders", "response " + res);
JSONArray mJsonArray = new JSONArray(res);
for (int i = 0; i < mJsonArray.length(); i++) {
if (i == 0 && mJsonArray.getJSONObject(i).has("info")) {
JSONObject object = mJsonArray.getJSONObject(i);
new Flags(getApplicationContext()).checkFlag(object.getString("info"));
} else {
JSONArray mJsonArrayItems = mJsonArray.getJSONArray(i);
Log.d("Responders", mJsonArrayItems.toString() + " - " + mJsonArrayItems.length());
for (int y = 0; i < mJsonArrayItems.length(); y++) {
Log.d("Responders", "inside");
JSONObject jsonObject = mJsonArrayItems.getJSONObject(y);
//String avatar = jsonObject.getString("profile_pic");
String username = jsonObject.getString("username");
//String full_name = jsonObject.getString("full_name");
//String department = jsonObject.getString("department");
String location = jsonObject.getString("coords");
responders.add(new ResponderObject("", username, "", "", location));
}
}
}
} catch (JSONException e) {
e.printStackTrace();
Log.d("Responders", "response " + e);
} catch (IOException e) {
e.printStackTrace();
error = true;
Log.d("Responders", "response " + e);
}
}
if (!error) {
handler.postDelayed(runnable, 3000);
if (!responders.isEmpty()) {
mapFragment.setResponders(responders);
if (location_enabled) {
//setting polyline
mapFragment.setPolyline();
}
respondersAdapter.notifyDataSetChanged();
}
} else {
handler.removeCallbacks(runnable);
}
}
#Override
public void onFailure(Call < ResponseBody > call, Throwable t) {
handler.removeCallbacks(runnable);
}
});
Here is the log I'm receiving for the mJsonArrayItems
`[{"username":"abcd.abcd","coords":"-2.9089067,56.4395"}] - 1` <b/>
You specified a wrong variable in the second loop. Try replacing:
for(int y = 0; i < mJsonArrayItems.length(); y++)
with
for(int y = 0; y < mJsonArrayItems.length(); y++)
i is 1, so 1 < mJsonArrayItems.length() is 1 < 1 and the loop never executes
I am trying to fetch campaign,ad level information from Facebook Using Graph API.
Campaign level information is getting with zero error for all accounts.
But for the Ad Level info, I am not getting the entire data. The API returns only 50. Remaining ads are getting with an exception called "Internal Server Error".
I've been getting this problem all day for one particular account. Every other Account works fine.
Below is the HTTP response:
response = (okhttp3.Response) Response{protocol=http/1.1, code=500, message=Internal Server Error,
url=https://graph.facebook.com/v3.3/act_fbAccountId/ads?access_token=myAccessToken&fields=%5B%22account_id%22%2C%22campaign_id%22%2C%22adset_id%22%2C%22id%22%2C%22bid_amount%22%2C%22name%22%2C%22status%22%2C%22preview_shareable_link%22%5D&limit=25&after=QVFIUkFzZAVdONXEwMXc5NjlOWURwczRQN0V3QW12NndRa0I4ZAUxsSjNkZA0FTRHR1U1dnaTQ5MTh2QnJ3bzNwWkNPd21jbC1tbjRmZAF81WVBsc0txaERCMHVn}
Below is the code
public List facebookAdsSynchThroughJson(String accessTokens, Long advertAccId, Properties googleStructureProperties, byte isOnScheduler, String appSecret) {
this.access_tokens = accessTokens;
this.appSecret = appSecret;
APIContext context = new APIContext(accessTokens, appSecret).enableDebug(true);
List<FacebookAdsStructure> adsList = new ArrayList<>();
String ads = "";
JSONObject advertIdObj = null;
JSONArray dataList = null;
ObjectMapper mapper = null;
boolean cond = true;
boolean success = false;
int limitValue = 100;
try {
while (cond) {
try {
AdAccount adAccount = new AdAccount(advertAccId, context).get().execute();
List adsFields = new ArrayList();
adsFields.add("account_id");
adsFields.add("campaign_id");
adsFields.add("adset_id");
adsFields.add("id");
adsFields.add("bid_amount");
adsFields.add("name");
adsFields.add("status");
adsFields.add("preview_shareable_link");
Map<String, Object> adsmap = new HashMap<>();
adsmap.put("fields", adsFields);
adsmap.put("limit", limitValue);
ads = adAccount.getAds().setParams(adsmap).execute().getRawResponseAsJsonObject().toString();
} catch (APIException ex) {
LOGGER.info("Exception thrown when fetching ads for Account Id: " + advertAccId + " with limit value: " + limitValue);
LOGGER.error(ex);
if (limitValue > 6) {
cond = true;
limitValue = limitValue / 2;
} else {
cond = false;
success = false;
break;
}
}
if (!ads.isEmpty()) {
cond = false;
success = true;
}
}
if (success) {
advertIdObj = new JSONObject(ads);
dataList = advertIdObj.getJSONArray("data");
mapper = new ObjectMapper();
adsList = mapper.readValue(dataList.toString(), new TypeReference<List<FacebookAdsStructure>>() {
});
JsonObject obj;
JsonParser parser = new JsonParser();
JsonElement result = parser.parse(ads);
obj = result.getAsJsonObject();
int maxTries = 1;
if (obj.has("data") && maxTries <= 5) {
while (obj.has("paging") && maxTries <= 5) {
JsonObject paging = obj.get("paging").getAsJsonObject();
if (paging.has("cursors")) {
JsonObject cursors = paging.get("cursors").getAsJsonObject();
String before = cursors.has("before") ? cursors.get("before").getAsString() : null;
String after = cursors.has("after") ? cursors.get("after").getAsString() : null;
}
String previous = paging.has("previous") ? paging.get("previous").getAsString() : null;
String next = paging.has("next") ? paging.get("next").getAsString() : "empty";
if (!next.equalsIgnoreCase("empty")) {
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(5, TimeUnit.MINUTES)
.writeTimeout(5, TimeUnit.MINUTES)
.readTimeout(5, TimeUnit.MINUTES)
.build();
Request request1 = new Request.Builder().url(next).get().build();
Response response = client.newCall(request1).execute();
if (response.isSuccessful()) {
maxTries = 1;
ads = response.body().string();
advertIdObj = new JSONObject(ads);
dataList = advertIdObj.getJSONArray("data");
mapper = new ObjectMapper();
List<FacebookAdsStructure> adsLists = new ArrayList<>();
adsLists = mapper.readValue(dataList.toString(), new TypeReference<List<FacebookAdsStructure>>() {
});
adsList.addAll(adsLists);
LOGGER.info("Fetched the Ad Structure.." + adsList.size());
parser = new JsonParser();
result = parser.parse(ads);
obj = result.getAsJsonObject();
} else {
LOGGER.info("Exception in response when fetching ads for Account Id: " + advertAccId + " , error response message: " + response.message() + " and with limit value: " + limitValue);
maxTries++;
if (maxTries >= 6) {
break;
}
try {
LOGGER.info("Thread Sleeping For 2 Minutes - Started for fb se_account_id " + advertAccId + " and maxTries = " + maxTries);
Thread.sleep(120000);
LOGGER.info("Thread Sleeping For 2 Minutes - Completed for fb se_account_id " + advertAccId + " and maxTries = " + maxTries);
} catch (InterruptedException ex) {
Logger.getLogger(FacebookAccountStructureSyncThroughJson.class.getName()).log(Level.SEVERE, null, ex);
}
}
} else {
obj = new JsonObject();
}
}
}
}
} catch (JsonSyntaxException | IOException | JSONException ex) {
LOGGER.error(ex);
}
return adsList;
}
If anybody knows anything about this issue, please help me.
getting values and trying to add to json array
public JSONArray getChooseContact(Context context ,String userid,String bookid , String chapterid, String questionid ) {
DBHelper dbh = new DBHelper(context , LektzDB.DB_NAME, null,
LektzDB.DB_VERSION);
SQLiteDatabase db = dbh.getReadableDatabase();
JSONArray resultSet = new JSONArray();
try{
Cursor cursor = db.rawQuery("SELECT * FROM "
+ TB_AssessmentChooseValues.NAME + " where "
+ TB_AssessmentChooseValues.CL_1_USER_ID + "='"+ userid +"' AND "
+ TB_AssessmentChooseValues.CL_2_BOOK_ID + "='"+ bookid +"' AND "
+ TB_AssessmentChooseValues.CL_3_CHAPTER_ID + "='" + chapterid +"' AND "
+ TB_AssessmentChooseValues.CL_4_QUESTION_ID + "='" + questionid + "'",null);
Log.i("logchoose", "gettingchooseSuccessful");
if(cursor.getCount() > 0) {
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
int totalColumn = cursor.getColumnCount();
JSONObject rowObject = new JSONObject();
for (int i = 0; i < totalColumn; i++) {
if (cursor.getColumnName(i) != null) {
try {
rowObject.put(cursor.getColumnName(i),
cursor.getString(i));
} catch (Exception e) {
Log.d("TAG", e.getMessage());
}
}
}
resultSet.put(rowObject);
cursor.moveToNext();
}
cursor.close();
}
}
catch(Exception e)
{
}
return resultSet;
}
and trying to retrieve values as
JSONArray RetrievedChoose = rdb.getChooseContact(getContext(),userid, BookId ,chapter_idchoose ,question_idchoose);
finalassessment.add(String.valueOf(RetrievedChoose));
Log.d("logchoose", "getsuccess"+finalassessment)
The cursor will get two rows of output but in json array im able to get only one value at a time.. I need this operation multiple times in my project please suggest me how to set that json array is not to be replaced for every time
The result is showing two seperate values which firstone is replacing second one
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
int totalColumn = cursor.getColumnCount();
JSONObject rowObject = new JSONObject();
for (int i = 0; i < totalColumn; i++) {
if (cursor.getColumnName(i) != null) {
try {
rowObject.put(cursor.getColumnName(i),
cursor.getString(i));
} catch (Exception e) {
Log.d("TAG", e.getMessage());
}
}
}
resultSet.put(rowObject);
}
cursor.close();
}
Use above code and return resultSet
I am getting the following error on logcat when I run my application. I had many errors before which I have managed to resolve after doing some research. However, this one I am unable to figure out:
03-04 02:52:29.475: E/JustDealsUtils(1913): Error parsing to json on getJarrayFromString(); org.json.JSONException: Expected ':' after result at character 8 of {result}
EDIT 1:
The error now is:
Error parsing to json on getJarrayFromString(); org.json.JSONException: Value result of type java.lang.String cannot be converted to JSONArray
Also linked to this is error for fillproductlist()
Here is my Java Code for this:
public void onTaskCompleted(String result) {
try {
if(result!=""){
// the remote php link
// converting the response into json array
Log.i(DEBUG, result);
jarray = utils.getJarrayFromString(result);
// number of rows in total for a query
int mysqlSize = (jarray.getJSONObject(0).getInt("numRows"));
Log.i(DEBUG, "From " + from + " to " + mysqlSize);
// to check if all the rows are parsed from the mysql
if(from <= mysqlSize){
int rows;
// to check if there is 0
if(jarray.length()>0){
Log.i(DEBUG, "From " + from + " to " + Math.floor(mysqlSize/nr)*nr);
if(from+5<=Math.floor(mysqlSize/nr)*nr){
rows = jarray.length();
}else{
rows = mysqlSize%nr+1;
Utils.IS_ENDED_PRODUCT_LIST = true;
}
ArrayList<String> list = new ArrayList<String>();
for(int i=1; i<rows; i++){
JSONObject row = jarray.getJSONObject(i);
bid.add(row.getInt("bid"));
bTitle.add(row.getString("bTitle"));
bCode.add(row.getString("bCode"));
bPrice.add(row.getString("bPrice") + "£");
bDescription.add(row.getString("bDescription"));
bModule.add(row.getString("bModule"));
bImage.add(Utils.PATH + row.getString("bImage"));
list.add(row.getString("bImage"));
// to check if an id already exists in the db or to create one if doesn't exist
if(!db.hasIDBooks(row.getInt("bid"))) db.createRowOnBooks(row.getInt("bid"), row.getString("bTitle"), row.getString("bCode"), row.getString("bPrice"), row.getString("bDescription"), row.getString("bModule"), Utils.PATH + row.getString("bImage"), row.getString("bSpecialOffer"), row.getInt("bSpecialDiscount"), row.getString("bDateAdded"));
Log.i(DEBUG, row.getString("bDescription"));
}
new DownloadImages(list, bAdapter).execute();
}
}
postParameters.removeAll(postParameters);
}else{
Utils.IS_ENDED_PRODUCT_LIST = true;
if(rlLoading.isShown()){
rlLoading.startAnimation(fadeOut());
rlLoading.setVisibility(View.INVISIBLE);
}
}
} catch (Exception e) {
Log.e(DEBUG, "Error at fillProductList(): " + e.toString());
}
}
});
task.execute();
}else{
// if internet connectio is not available
// then, rows will be fetched from the local sqllite database stored on the android phone
if(db.size(justdealsDatabase.TABLE_BOOKS) > 0){
Cursor cursor = db.getBooksRows(justdealsDatabase.TABLE_BOOKS);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
bid.add(cursor.getInt(cursor.getColumnIndex(justdealsDatabase.KEY_BID)));
bTitle.add(cursor.getString(cursor.getColumnIndex(justdealsDatabase.KEY_BTITLE)));
bCode.add(cursor.getString(cursor.getColumnIndex(justdealsDatabase.KEY_BCODE)));
bPrice.add(cursor.getString(cursor.getColumnIndex(justdealsDatabase.KEY_BPRICE))+ "£");
bDescription.add(cursor.getString(cursor.getColumnIndex(justdealsDatabase.KEY_BDESCRIPTION)));
bModule.add(cursor.getString(cursor.getColumnIndex(justdealsDatabase.KEY_BMODULE)));
bImage.add(cursor.getString(cursor.getColumnIndex(justdealsDatabase.KEY_BIMAGE)));
cursor.moveToNext();
}
bAdapter.notifyDataSetChanged();
Utils.IS_ENDED_PRODUCT_LIST = true;
}
}
}
MY JSON ARRAY CODE ( FULL EDIT 2):
public String getJsonFromUrl(String url){
// to initialise the objects
InputStream is = null;
String result = "";
//making HTTP POST request
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e(DEBUG, "Error getJsonFromUrl: " + e.toString());
}
// Converting to String
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e(DEBUG, "Error converting the response to string getJsonFromUrl: " + e.toString());
}
return result;
}
/**
* To convert the string recieved into json object
* result refers to the string that will be converted
* #return will return the json array
*/
public JSONArray getJarrayFromString(String result){
// Parsing string to JSON Array
try{
jarray = new JSONArray("result");
}catch(JSONException e){
Log.e(DEBUG, "Error parsing to json on getJarrayFromString(); " + e.toString());
}
return jarray;
}
And My PHP API (EDIT 1):
<?php
include("MysqlConnection.php");
header('Content-Type: application/json');
$from = $_POST["from"];
$nr = $_POST["nr"];
// those variables are for search
$title = $_POST["title"];
$code = $_POST["code"];
$price = $_POST["price"];
$module = $_POST["module"];
$order = $_POST["order"];
$by = $_POST["by"];
$sql = "SET CHARACTER SET utf8";
$db->query($sql);
// if those 2 var are set then we order the query after them
if(isset($order) && isset($by)){
$sql .= " ORDER BY `$order` $by LIMIT $from, $nr";
}else{
$sql .= "LIMIT $from, $nr";
}
$query = $db->query($sql);
$rows = array();
$rows[] = array("numRows"=>$db->numRows($query));
if($db->numRows($query)!=0){
while($row = mysql_fetch_assoc($query)) {
$rows[] = $row;
}
echo(json_encode($rows));
}
}
$db->closeConnection();
?>
I have implemented all the suggestions recommended by you guys, still there is no luck in getting this code work!!!!
I AM NOT SURE WHY VALUE OF 'RESULT' STRING CANNOT BE CONVERTED INTO JSONARRAY????
I have shown you the JSON ARRAY Declaration, RESULT STRING DECLARATION as well as PHP (See Above for edited versions)
you have to use echo not print_r
echo json_encode($rows);
print_r gives output in array format.
You have send the result two times you have to send the result only one time with encoded
remove the following code and try
echo json_encode($rows);
Maybe you should name your array without "{}" symbols?
jarray = new JSONArray("result");
instead of
jarray = new JSONArray("{result}");
I implemented this code below in order to read contacts from the addressbook of the phone
The problem is, In a case when all the numbers in the phonebook are saved in the SIM it reads and displays the contacts for selection.
But in a case whereby any number is included on the phone memory, it gives an application error.(OutOfMemoryException)
What do I do (PS do not mind some System.out.println statements there. I used them for debugging)
public void execute() {
try {
// go through all the lists
String[] allContactLists = PIM.getInstance().listPIMLists(PIM.CONTACT_LIST);
if (allContactLists.length != 0) {
for (int i = 0; i < allContactLists.length; i++) {
System.out.println(allContactLists[i] + " " + allContactLists[1]);
System.out.println(allContactLists.length);
loadNames(allContactLists[i]);
System.out.println("Execute() error");
}
} else {
available = false;
}
} catch (PIMException e) {
available = false;
} catch (SecurityException e) {
available = false;
}
}
private void loadNames(String name) throws PIMException, SecurityException {
ContactList contactList = null;
try {
// ----
// System.out.println("loadErr1");
contactList = (ContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_ONLY, name);
// System.out.println(contactList.getName());//--Phone Contacts or Sim Contacts
// First check that the fields we are interested in are supported(MODULARIZE)
if (contactList.isSupportedField(Contact.FORMATTED_NAME)
&& contactList.isSupportedField(Contact.TEL)) {
// ContactLst.append("Reading contacts...", null);
// System.out.println("sup1");
Enumeration items = contactList.items();
// System.out.println("sup2");
Vector telNumbers = new Vector();
telNames = new Vector();
while (items.hasMoreElements()) {
Contact contact = (Contact) items.nextElement();
int telCount = contact.countValues(Contact.TEL);
int nameCount = contact.countValues(Contact.FORMATTED_NAME);
// System.out.println(telCount);
// System.out.println(nameCount);
// we're only interested in contacts with a phone number
// nameCount should always be > 0 since FORMATTED_NAME is
// mandatory
if (telCount > 0 && nameCount > 0) {
String contactName = contact.getString(Contact.FORMATTED_NAME, 0);
// go through all the phone numbers
for (int i = 0; i < telCount; i++) {
System.out.println("Read Telno");
int telAttributes = contact.getAttributes(Contact.TEL, i);
String telNumber = contact.getString(Contact.TEL, i);
System.out.println(telNumber + " " + "tel");
// check if ATTR_MOBILE is supported
if (contactList.isSupportedAttribute(Contact.TEL, Contact.ATTR_MOBILE)) {
if ((telAttributes & Contact.ATTR_MOBILE) != 0) {
telNames.insertElementAt(telNames, i);
telNumbers.insertElementAt(telNumber, i);
} else {
telNumbers.addElement(telNumber);
telNames.addElement(telNames);
}
}
// else {
//// telNames.addElement(contactName);
// telNumbers.addElement(telNumber);
// }
System.out.println("telephone nos");
}
// Shorten names which are too long
shortenName(contactName, 20);
for (int i = 0; i <= telNumbers.size(); i++) {
System.out.println(contactName + " here " + telNames.size());
telNames.addElement(contactName);
System.out.println(telNames.elementAt(i) + " na " + i);
}
names = new String[telNames.size()];
for (int j = 0; j < names.length; j++) {
names[j] = (String) telNames.elementAt(j);
System.out.println(names[j] + "....");
}
// allTelNames.addElement(telNames);
System.out.println("cap :" + telNames.size() + " " + names.length);
// telNames.removeAllElements();
// telNumbers.removeAllElements();
}
}
available = true;
} else {
// ContactLst.append("Contact list required items not supported", null);
available = false;
}
} finally {
// always close it
if (contactList != null) {
contactList.close();
}
}
}