Initialize the value of a arraylist - android

I can't understand what is wrong in my code . I am getting error in myAddressUniqueness. don't know why.Before i have tried it with string data type but got the same error. It is saying java.null exception.
ArrayList<String> myAddressUniqueness = null;
String name = "hello";
if (indexBody < 0 || !cursor.moveToFirst())
return;
smsList.clear();
do {
// int cursorPostion = cursor.getPosition();
String address;
String msgStr = cursor.getString(indexBody);
String senderNumber = cursor.getString(indexAddr);
Log.d("Name : ", senderNumber);
// String name = cursor.getString(cursor
// .getColumnIndex(PhoneLookup.DISPLAY_NAME));
// Log.d("Name : ",name);
if (name != null) {
address = name;
} else {
address = senderNumber;
}
Log.d("Address: ", address);
flag = 1;
//Log.e("Number: ", addressUniqueness.length + "");
for (j = 0; j < myAddressUniqueness.size(); j++) {
if (myAddressUniqueness.contains(address)) {
flag = 0;
break;
}
}
if (flag == 1) {
myAddressUniqueness.add(new String(address));
i++;
String str = "Sender: " + address + "\n";
smsList.add(str);
}
// TODO Auto-generated catch block
} while (cursor.moveToNext());

Change your declaration to
ArrayList<String> myAddressUniqueness = new ArrayList<String>();
You have it initialized to null. This will instantiate it then you can add data to it.

You should instantiate myAddressUniqueness by myAddressUniqueness = new ArrayList<String>() before using it.

Related

IndexOutOfRangeException: Array index is out of range. DataCache.GetAchievementCacheData () (at Assets/Scripts/Mission/Plugin/DataCache.cs:329)

When I run the game using unity I get this error continuously in the console window and the loading screen is not going further next. Help me to fix this issue.
IndexOutOfRangeException: Array index is out of range.
DataCache.GetAchievementCacheData () (at
Assets/Scripts/Mission/Plugin/DataCache.cs:329)
Here is my code below
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using UnityEngine;
//Class luu mission current
public class CurrentMission
{
public string FB_id { get; set; }
public string Name { get; set; }
public string Mission { get; set; }
public CurrentMission(string id, string name, string mission)
{
this.FB_id = id;
this.Name = name;
this.Mission = mission;
}
public CurrentMission()
{
this.FB_id = "";
this.Name = "";
this.Mission = "";
}
}
public class MissionDataSave
{
public int Mission;
public long Score;
public int Star;
public int Open;//0-false. 1-true
public MissionDataSave(int mission, long score, int star, int open)
{
Mission = mission;
Score = score;
Star = star;
Open = open;
}
public MissionDataSave()
{
Mission = 0;
Score = 0;
Star = 0;
Open = 0;
}
}
public class AchievementCache
{
//group nhiem vu
public int Group;
//Level hien tai cua group
public int Level;
//Gia tri hien tai
public int Value;
//Thong bao mission hoan thanh
public int Notify;//0 - False, 1 - true
//public AchievementCache()
//{
// this.Group = 1;
// this.Level = 1;
// this.Value = 0;
//}
public AchievementCache(int group, int level, int value, int notify)
{
this.Group = group;
this.Value = value;
this.Level = level;
this.Notify = notify;
}
public AchievementCache()
{
this.Group = 1;
this.Value = 0;
this.Level = 1;
this.Notify = 0;
}
}
public class DataCache
{
public static string FB_ID = "FB_ID";
public static string FB_USER = "FB_USER";
public static string Achievement_data_key = "Achievement_data_key";
public static string Mission_data_key = "Mission_data_key";
public static string Current_mission_data_key = "Current_mission_data_key";
public static AchievementCache[] dataAchievementCache;
public static MissionDataSave[] dataMissionCache;
public static CurrentMission[] dataCurrentMissionCache;
//public static string XML_Current_Mission_Path = "CurrentMissionSave.xml";
//public static string XML_Data_Mission_Path = "DataMissionSave.xml";
//public static string XML_Data_Achievement_Path = "AchievementCache.xml";
//serialize xml theo tung phan tu
//public static List<MissionDataSave> DeserializeMissionDataSaveListFromXML(string filePath)
//{
// if (!System.IO.File.Exists(filePath))
// {
// Debug.LogError("File " + filePath + " not exist!");
// return new List<MissionDataSave>();
// }
// XmlSerializer deserializer = new XmlSerializer(typeof(List<MissionDataSave>), new XmlRootAttribute("MissionDataSaveRoot"));
// TextReader textReader = new StreamReader(filePath);
// List<MissionDataSave> movies = (List<MissionDataSave>)deserializer.Deserialize(textReader);
// textReader.Close();
// return movies;
//}
//public static void readXMLTest()
//{
// string xmlDataCache1 = Application.persistentDataPath + "/" + XML_Current_Mission_Path;
// TextReader textReader = new StreamReader(xmlDataCache1);
// XmlDocument xmlDoc = new XmlDocument();
// xmlDoc.Load(textReader);
// XmlNodeList xmlNodeList = xmlDoc.DocumentElement.ChildNodes;
// Debug.Log("TRUOC");
// foreach (XmlNode node in xmlNodeList)
// {
// Debug.Log("aaaaaaaaaaaaaaaaaaaaa " + node.Attributes["Id"].Value);
// }
// Debug.Log("SAU");
// XmlNode root = xmlDoc.DocumentElement;
// XmlElement elem = xmlDoc.CreateElement("CurrentMissionCache");
// elem.SetAttribute("Id", "112312");
// elem.SetAttribute("Name", "NameDG");
// elem.SetAttribute("Mission", "MissionDG");
// root.AppendChild(elem);
// textReader.Close();
// xmlDoc.Save(xmlDataCache1);
//}
//Add mission xml node
public static void UpdateMissionScore(long score, int star, int mission, int open)
{
MissionDataSave data = dataMissionCache[mission - 1];
if (data.Star < star)
{
data.Star = star;
}
if (data.Score < score)
{
data.Score = score;
}
data.Open = open;
}
public static void SaveMissionDataCache(bool submitToServer = false)
{
string dataSave = "";
string dataSendServer = "";
for (int i = 0; i < dataMissionCache.Length; i++)
{
dataSave += dataMissionCache[i].Mission + "-" + dataMissionCache[i].Score + "-" + dataMissionCache[i].Star + "-" + dataMissionCache[i].Open + ",";
//Chi gui nhung mission da open len server
if (dataMissionCache[i].Open == 1)
{
if (dataSendServer.Length > 0)
dataSendServer += ",";
dataSendServer += dataMissionCache[i].Mission + "-" + dataMissionCache[i].Score + "-" + dataMissionCache[i].Star + "-" + dataMissionCache[i].Open;
}
}
Debug.Log("Data save " + dataSave);
PlayerPrefs.SetString(Mission_data_key, dataSave);
if (submitToServer)
{
Debug.Log("Data send server " + dataSendServer);
AudioControl.getMonoBehaviour().StartCoroutine(DHS.PostMeInfoMissionUpdate(FB.UserId, dataSendServer));
}
}
public static void GetMissionDataCache()
{
int max_mission = 100;
if (dataMissionCache != null)
{
dataMissionCache = null;
}
dataMissionCache = new MissionDataSave[max_mission];
//Tao moi neu chua co
if (!PlayerPrefs.HasKey(Mission_data_key))
{
string datas = "1-0-0-1,";
for (int i = 2; i <= max_mission; i++)
{
//Mission - Score - Star - Open
if (DataMissionControlNew.test)
{
datas += i + "-0-0-1,";
//if (i < 16)
// datas += i + "-0-0-1,";
//else datas += i + "-0-0-0,";
}
else
{
datas += i + "-0-0-0,";
}
}
PlayerPrefs.SetString(Mission_data_key, datas);
}
string missionData = PlayerPrefs.GetString(Mission_data_key);
string[] data = missionData.Split(',');
for (int i = 0; i < max_mission; i++)
{
string[] infoData = data[i].Split('-');
//Debug.Log("Info " + data[i]);
string mission = infoData[0];
string score = infoData[1];
string star = infoData[2];
string open = infoData[3];
dataMissionCache[i] = new MissionDataSave(Convert.ToUInt16(mission), Convert.ToUInt32(score), Convert.ToUInt16(star), Convert.ToUInt16(open));
}
}
//-------------------------CURRENT MISSION---------------------------
//Add current mission xml node
public static void SaveCurrentMission(string data = "")
{
if (String.IsNullOrEmpty(data))
{
string dataSave = "";
for (int i = 0; i < dataCurrentMissionCache.Length; i++)
{
if (dataSave.Length > 0)
dataSave += ",";
dataSave += dataCurrentMissionCache[i].FB_id + "-" + dataCurrentMissionCache[i].Name + "-" + dataCurrentMissionCache[i].Mission;
}
PlayerPrefs.SetString(Current_mission_data_key, dataSave);
}
else
{
PlayerPrefs.SetString(Current_mission_data_key, data);
GetCurrentMission();
}
}
public static void GetCurrentMission()
{
if (!PlayerPrefs.HasKey(Current_mission_data_key))
{
PlayerPrefs.SetString(Current_mission_data_key, "Me-User-1");
}
if (dataCurrentMissionCache != null)
{
dataCurrentMissionCache = null;
}
string current_data = PlayerPrefs.GetString(Current_mission_data_key);
string[] data = current_data.Split(',');
dataCurrentMissionCache = new CurrentMission[data.Length];
for (int i = 0; i < data.Length; i++)
{
string[] info = data[i].Split('-');
//fb - User name - missison
dataCurrentMissionCache[i] = new CurrentMission(info[0], info[1], info[2]);
}
}
public static void SetMeCurrentMission(int mission)
{
for (int i = 0; i < DataCache.dataCurrentMissionCache.Length; i++)
{
if ("Me".Equals(DataCache.dataCurrentMissionCache[i].FB_id))
{
int old = Convert.ToInt16(DataCache.dataCurrentMissionCache[i].Mission);
if (old < mission)
{
DataCache.dataCurrentMissionCache[i].Mission = "" + mission;
DataCache.UpdateMissionScore(0, 0, mission, 1);//Them mission moi vao xml
}
}
}
DataCache.SaveCurrentMission();
}
//-------------------------ACHIEVEMENT---------------------------
//Ghi de len du lieu cu
public static void ReplaceAchievementCache(int groupLevel, int value, int level = -1)
{
dataAchievementCache[groupLevel - 1].Value = value;
if (level != -1)
{
dataAchievementCache[groupLevel - 1].Level = level;
}
}
//Cap nhat them du lieu
public static void AddAchievementCache(int groupLevel, int addValue, int addLevel = 0)
{
dataAchievementCache[groupLevel - 1].Level += addLevel;
dataAchievementCache[groupLevel - 1].Value += addValue;
}
public static void GetAchievementCacheData()
{
Debug.Log("-------------GetAchievementCacheData--------------------");
if (dataAchievementCache != null)
{
dataAchievementCache = null;
}
dataAchievementCache = new AchievementCache[22];
//Tao achievement
if (!PlayerPrefs.HasKey(Achievement_data_key))
{
string achi = "";
for (int i = 1; i <= 22; i++)
{
achi += i + "-1-0-0,";
}
//Debug.Log("Create new achievement " + achi);
PlayerPrefs.SetString(Achievement_data_key, achi);
}
string achievement = PlayerPrefs.GetString(Achievement_data_key);
//Debug.Log(achievement);
string[] achie = achievement.Split(',');
for (int i = 0; i< dataAchievementCache.Length; i++)
{
//Debug.Log(achie[i]);
string[] infoAchie = achie[i].Split('-');
string group = infoAchie[0];
string level = infoAchie[1];
string value = infoAchie[2];
string notify = infoAchie[3];
//Debug.Log(group +" " + dataAchievementCache[i].Group);
dataAchievementCache[i] = new AchievementCache();
dataAchievementCache[i].Group = Convert.ToInt16(group);
dataAchievementCache[i].Level = Convert.ToInt16(level);
dataAchievementCache[i].Value = Convert.ToInt32(value);
dataAchievementCache[i].Notify = Convert.ToInt16(notify);
}
}
public static void SaveAchievementCache(bool sendServer = false)
{
try
{
Debug.Log("-------------------SaveAchievementCache-----------------");
if (dataAchievementCache != null)
{
string achievement = "";
for (int i = 0; i < dataAchievementCache.Length; i++)
{
string s = "" + dataAchievementCache[i].Group + "-" + dataAchievementCache[i].Level + "-" + dataAchievementCache[i].Value + "-" + dataAchievementCache[i].Notify + ",";
achievement += s;
}
//Debug.Log("----------LUU ACHIEVEMENT------------ " + achievement);
PlayerPrefs.SetString(Achievement_data_key, achievement);
if (FB.IsLoggedIn && sendServer)
{
//Nếu chưa có playerprefs thì sẽ submit lên luôn
//Nếu có rồi thì phải check nó cập nhật hoàn thành từ server về thì mới cho up lên
bool check = !PlayerPrefs.HasKey(DataMissionControlNew.key_update_achievement_data_from_server) ||
(PlayerPrefs.HasKey(DataMissionControlNew.key_update_achievement_data_from_server) && PlayerPrefs.GetInt(DataMissionControlNew.key_update_achievement_data_from_server) == 1);
if (check)
{
AudioControl.getMonoBehaviour().StartCoroutine(DHS.PostMeInfoUpdate(DFB.UserId, "" + VariableSystem.diamond, "" + achievement, "", (www) =>
{
Debug.Log("----------Update achievement to server success!------------- " + achievement);
}));
}
else
{
Debug.Log("----------KHONG CHO UP ACHIEVEMENT VA DIAMOND LEN SERVER------------- " + PlayerPrefs.GetInt(DataMissionControlNew.key_update_mission_data_from_server, 0));
}
}
}
}
catch (Exception e)
{
Debug.Log("------------ERROR ---------------" + e.Message);
if (DataMissionControlNew.test)
{
MobilePlugin.getInstance().ShowToast("ERROR " + e.Message);
}
}
}
public static void DeleteUserData()
{
PlayerPrefs.DeleteKey(FB_ID);
PlayerPrefs.DeleteKey(Mission_data_key);
PlayerPrefs.DeleteKey(Current_mission_data_key);
PlayerPrefs.DeleteKey(Achievement_data_key);
PlayerPrefs.DeleteKey("diamond");
PlayerPrefs.DeleteKey(DataMissionControlNew.key_update_mission_data_from_server);
VariableSystem.diamond = 8;
VariableSystem.heart = 5;
}
public static void RestoreUserData(int diamond, string achievement)
{
Debug.Log("Restore user data");
VariableSystem.diamond = diamond;
VariableSystem.heart = PlayerPrefs.GetInt("heart", 5);
string[] achie = achievement.Split(',');
if (achie.Length > 5)
{
for (int i = 0; i < dataAchievementCache.Length; i++)
{
string[] infoAchie = achie[i].Split('-');
string group = infoAchie[0];
string level = infoAchie[1];
string value = infoAchie[2];
string notify = infoAchie[3];
dataAchievementCache[i].Group = Convert.ToInt16(group);
dataAchievementCache[i].Level = Convert.ToInt16(level);
dataAchievementCache[i].Value = Convert.ToInt32(value);
dataAchievementCache[i].Notify = Convert.ToInt16(notify);
}
//Debug.Log("---Luu achievement----");
SaveAchievementCache();
GetAchievementCacheData();
}
Debug.Log("----------------ACHIEVEMENT da dc cap nhat tu -----------------");
PlayerPrefs.SetInt(DataMissionControlNew.key_update_achievement_data_from_server, 1);
}
The line 329 is this
string level = infoAchie[1];
The problem is coming from the last comma you are adding in the string you are adding to your PlayerPrefs in this part:
if (!PlayerPrefs.HasKey(Achievement_data_key))
{
string achi = "";
for (int i = 1; i <= 22; i++)
{
achi += i + "-1-0-0,";
}
//Debug.Log("Create new achievement " + achi);
PlayerPrefs.SetString(Achievement_data_key, achi);
}
This code generates this string:
1-1-0-0,2-1-0-0,3-1-0-0,4-1-0-0,5-1-0-0,6-1-0-0,7-1-0-0,8-1-0-0,9-1-0-0,10-1-0-0,11-1-0-0,12-1-0-0,13-1-0-0,14-1-0-0,15-1-0-0,16-1-0-0,17-1-0-0,18-1-0-0,19-1-0-0,20-1-0-0,21-1-0-0,22-1-0-0,
Keep in memory that last comma at the end of the string.
You are later doing a split on the ',' character, and iterating over them.
string[] achie = achievement.Split(',');
for (int i = 0; i< dataAchievementCache.Length; i++)
{
//Debug.Log(achie[i]);
string[] infoAchie = achie[i].Split('-');
string group = infoAchie[0];
string level = infoAchie[1];
...
}
The problem is that by doing so, your achie string array contains an empty last element. So when you are later splitting on the "-" character, your infoAchie string array only contains one element: the empty string. The first line:
string group = infoAchie[0];
Still works, but is filled with the empty string. Then:
string level = infoAchie[1];
Can't work, as you are indeed out of the bounds of the infoAchie array.
The solution would be to add the comma to your string only if it is not the last element.
Also, I strongly advise you to use a StringBuilder over a simple string for optimization purposes. Your code could then look like, for instance:
if (!PlayerPrefs.HasKey(Achievement_data_key))
{
StringBuilder achi = new StringBuilder();
for (int i = 1; i <= 22; i++)
{
achi.Append(i).Append("-1-0-0");
if(i != 22)
achi.Append(",");
}
//Debug.Log("Create new achievement " + achi);
PlayerPrefs.SetString(Achievement_data_key, achi.ToString());
}
Which generates this string:
1-1-0-0,2-1-0-0,3-1-0-0,4-1-0-0,5-1-0-0,6-1-0-0,7-1-0-0,8-1-0-0,9-1-0-0,10-1-0-0,11-1-0-0,12-1-0-0,13-1-0-0,14-1-0-0,15-1-0-0,16-1-0-0,17-1-0-0,18-1-0-0,19-1-0-0,20-1-0-0,21-1-0-0,22-1-0-0

How to print a string if data is not available on server in android using json

Thank you guys.Finally i got the solution.If we want to check whether string is empty or null we must trim() the string.
String url="http://app name/Api/GetJobDetails/GetJobDetails?COMP_REQ_ID=" + title + "&StuEmail=" + e ; // this is the url
AQuery mAQuery = new AQuery(SecondActivity.this);
mAQuery.ajax(url, String.class, new AjaxCallback<String>() {
public Object dataSource;
#Override
public void callback(String url, String data, AjaxStatus status)
{
uper.callback(url, data, status);
if (null != data && status.getCode() != -101) {
String StringData = "" + data;
try {
JSONArray rootArray = new JSONArray(StringData);
int len = rootArray.length();
for (int i = 0; i < len; ++i) {
JSONObject json = rootArray.optJSONObject(i);
String Salary = json.optString("Req_From_Sal");
if (Salary == null || Salary.trim().equals("null") || Salary.trim().length() <= 0) {
b14.setText("Not Mentioned");
}
else
{
b14.setText(""+Salary);
}
}
}
}
});
Check you string if it is null or blank then print message what you want. For example:
if(StringData.length()==0){
//show message
}else{
JSONArray rootArray = new JSONArray(StringData);
int len = rootArray.length();
for (int i = 0; i < len; ++i) {
JSONObject json = rootArray.optJSONObject(i);
String Salary = json.optString("Req_From_Sal");
if (Salary == null)
b14.setText("NA"+Salary);
else
b14.setText(""+Salary)
}
}
MoreOver if you want to show specific message for specific user then ask for the success parameter. If success==1 go for you logic else if success ==0 then ask for message parameter as well parse it and show it to user
1.Check whether StringData is null or empty.
2.Check if rootArray.length()==0
Try this.
if(StringData!=null) {
JSONArray rootArray = new JSONArray(StringData);
for (int i = 0; i < rootArray.length(); ++i) {
JSONObject json = rootArray.optJSONObject(i);
String Job_Title = json.optString("Req_Title", "default_value");
String Designation = json.optString("Req_Designation_Role", "default_value");
String Salary = json.optString("Req_From_Sal", "Salary Not Mentioned");
b14.setText("" + Salary);
}
}else{
Log.d(TAG, "Invalid JSON Data");
b14.setText("Salary Not Mentioned");
}
USe TextUtils.isEmpty() to check for null and empty string.
Always add null check before getting any variable from object.
Modified code below:
JSONArray rootArray = new JSONArray(StringData);
if(rootArray!=null&&rootArray.length())
{
int len = rootArray.length();
for (int i = 0; i < len; ++i)
{
JSONObject json = rootArray.optJSONObject(i);
if (json != null) {
String Job_Title = json.optString("Req_Title");
String Designation = json.optString("Req_Designation_Role");
String Job_Type = json.optString("Req_Job_Type");
String Salary;
if (json.has("Req_From_Sal") && !TextUtils.isEmpty(json.getString("Req_From_Sal")) {
Salary = json.optString("Req_From_Sal");
} else {
Salary = "Not available";
}
b14.setText(Salary);
}
}
}
Thank you guys.Finally i got the solution. Here is edit code.To check the String is null or empty we should have to trim() the string.
Android side:-
String url="http://app name/Api/GetJobDetails/GetJobDetails?COMP_REQ_ID=" + title + "&StuEmail=" + e ; // this is the url
AQuery mAQuery = new AQuery(SecondActivity.this);
mAQuery.ajax(url, String.class, new AjaxCallback<String>() {
public Object dataSource;
#Override
public void callback(String url, String data, AjaxStatus status) {
uper.callback(url, data, status);
if (null != data && status.getCode() != -101) {
String StringData = "" + data;
try {
JSONArray rootArray = new JSONArray(StringData);
int len = rootArray.length();
for (int i = 0; i < len; ++i) {
JSONObject json = rootArray.optJSONObject(i);
String Job_Title = json.optString("Req_Title");
String Designation = json.optString("Req_Designation_Role");
String Job_Type = json.optString("Req_Job_Type");
String Salary = json.optString("Req_From_Sal");
if(Job_Title == null || Job_Title .trim().equals("null") ||Job_Title .trim().length<=0){
b1.setText("Job title not set.");
}else{
b1.setText("" +Job_Title);
}
if(Designation == null || Designation.trim().equals("null") ||Designation.trim().length() <= 0){
b3.setText("Job Designation not set.");
}else{
b3.setText("" +Designation);
}
if(Job_Type == null || Job_Type.trim().equals("null") || Job_Type.trim().length() <= 0){
b13.setText("Job Type not set.");
}else{
b13.setText("" +Job_Type);
}
if(Salary == null || Salary.trim().equals("null") || Salary.trim().length() <= 0){
b14.setText("Not yet Mentioned");
}else{
b14.setText(""+Salary);
}
}
}
}
});

how do i load swipe to refresh data at top listview android

Currently, my listview shows me current data. On Swipe, it will load old data from the server and store first old data and after current data. load server data at the top while swipe to refresh data. it is no updating data at the top level. Help me out for this situation. every time load data on top. and show loader while refreshing data while swipe to top to bottom.
Thank you in advance. Here I am posting my code for review
public class CommmentActivity extends Activity{
String Curl;
boolean mBuzy;
String UserId;
String VidoId;
String strComment;
EditText etComment;
String mPositionId = "";
String strfriendsSyncDate;
ArrayAdapter<String> mentionList;
ListCommentAdapter commentAdapter;
AutoCompleteTextView aCompletView;
DatabaseHandler db = new DatabaseHandler(this);
List<CommentListInfo> list_CommentInfo = new ArrayList<CommentListInfo>();
ArrayList<MentionBeanClass> mList;
MentionBeanClass addMention;
List<String> SuggetionList;
ImageView IvAddComment;
ListView CommentList;
SessionCreator m_session;
boolean m = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.commentvideo_main);
SuggetionList = new ArrayList<String>();
Curl = GlobalMethod.TokenGenerator() + "&action=getCommentsVideo";
Intent data = getIntent();
UserId = data.getStringExtra("userId");
VidoId = data.getStringExtra("videoId");
init();
strfriendsSyncDate = m_session.getfriendsSyncDate();
new CommentsDetail().execute(UserId,VidoId,strfriendsSyncDate,mPositionId,Curl,"1");
ArratListBeans.setArMentionList(mList);
commentAdapter = new ListCommentAdapter(getApplicationContext(), list_CommentInfo);
CommentList.setAdapter(commentAdapter);
CommentList.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
switch (scrollState) {
case OnScrollListener.SCROLL_STATE_IDLE:{
Log.d("ScrollStateCheck", ""+scrollState);
break;
}
case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
{
mBuzy = true;
int count = CommentList.getCount();
if(CommentList.getFirstVisiblePosition()==0){
CommentListInfo c;
c = (CommentListInfo) CommentList.getAdapter().getItem(CommentList.getFirstVisiblePosition());
mPositionId = c.CommentId;
Log.d("mpositionId", mPositionId);
String strUrl = GlobalMethod.TokenGenerator() + "&action=getCommentsVideo";
new CommentsDetail().execute(UserId,VidoId,strfriendsSyncDate,c.CommentId,strUrl,"1");
}
break;
}
case OnScrollListener.SCROLL_STATE_FLING:{
mBuzy = true;
break;
}
default:
break;
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
}
});
IvAddComment.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
strComment = etComment.getText().toString();
etComment.getText().clear();
String strUrl = GlobalMethod.TokenGenerator() + "&action=addCommentsVideo";
new CommentsDetail().execute(UserId,VidoId,strComment,strUrl,"0");
new CommentsDetail().execute(UserId,VidoId,strfriendsSyncDate,Curl,"1");
commentAdapter.notifyDataSetChanged();
}
});
}
private void init() {
// TODO Auto-generated method stub
m_session = new SessionCreator(getApplicationContext());
etComment = (EditText)findViewById(R.id.etComments);
CommentList = (ListView)findViewById(R.id.lvLatestComments);
IvAddComment = (ImageView)findViewById(R.id.addComment);
mList = new ArrayList<MentionBeanClass>();
}
public class CommentsDetail extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
ServiceHandler serviceClient;
String mJsonString;
try{
String userId = (String)params[0];
String vId = (String)params[1];
String syncdate = (String)params[2];
String startPosition = (String)params[3];
String strUrl = (String)params[4];
List<NameValuePair> paramsNameValuePairs = new ArrayList<NameValuePair>();
paramsNameValuePairs.add(new BasicNameValuePair("userId", userId));
paramsNameValuePairs.add(new BasicNameValuePair("videoId", vId));
paramsNameValuePairs.add(new BasicNameValuePair("startFrom", startPosition));
paramsNameValuePairs.add(new BasicNameValuePair("friendsSyncDate", syncdate));
serviceClient = new ServiceHandler();
mJsonString = serviceClient.makeServiceCall(strUrl,
ServiceHandler.POST, paramsNameValuePairs);
Log.i("---->>>>>>>>>>", paramsNameValuePairs + "");
Log.d("Response Json-----------------------",mJsonString );
return mJsonString;
}catch (Exception e) {
e.getStackTrace();
}
return null;
}
#SuppressWarnings({ "unchecked", "unchecked", "unchecked" })
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
try{
if (result != null) {
JSONObject responsJsonObj = new JSONObject(result);
JSONObject jsonObj = (JSONObject) responsJsonObj
.optJSONObject("data");
try {
String str = jsonObj.getString("error");
if ( str != null || str.length() != 0) {
// error
//Toast.makeText(NewsfeedActivity.this, jsonObj.getString("error"),Toast.LENGTH_LONG).show();
return;
}
} catch (JSONException je) {
Log.d("jex ------>", "" + je.getMessage());
try {
String str = jsonObj.getString("message");
Log.d("message=", "" + str);
if ( str != null || str.length() != 0) {
// VALID RESPONSE, NOW PARSE IT
if (jsonObj.has("comments")) {
JSONArray colArray = jsonObj.getJSONArray("comments");
Log.d("Colunm Array", ""+colArray);
int nComments = colArray.length();
Log.d("# comments", "" + nComments);
for(int i=0; i<nComments; i++){
JSONObject obj = colArray.getJSONObject(i);
Gson Comments = new Gson();
String strComments = Comments.toJson(obj);
Log.d("# obj=", "" + obj.toString());
CommentListInfo cmtInfo = new CommentListInfo();
cmtInfo.c_userId = obj.getString("userId");
cmtInfo.c_name = obj.getString("name");
cmtInfo.DateAdded = obj.getString("dateAdded");
cmtInfo.CommentId = obj.getString("commentId");
cmtInfo.CommentText = obj.getString("text");
cmtInfo.ImageUrl = obj.getString("imageLink");
list_CommentInfo.add(cmtInfo);
}
}
}
if ( str != null || str.length() != 0) {
// VALID RESPONSE, NOW PARSE IT
if (jsonObj.has("addPosition")) {
Log.d("# obj=", "" + jsonObj.toString());
Log.d("Add Position", jsonObj.getString("addPosition"));
}
}
if ( str != null || str.length() != 0) {
// VALID RESPONSE, NOW PARSE IT
if (jsonObj.has("mentions")) {
JSONArray colArray = jsonObj.getJSONArray("mentions");
Log.d("Colunm Array", ""+colArray);
int nMention = colArray.length();
Log.d("# mentions", "" + nMention);
for(int i=0; i<nMention; i++){
JSONObject obj = colArray.getJSONObject(i);
Log.d("# obj=", "" + obj.toString());
mList.add(new MentionBeanClass(obj.getString("id"), obj.getString("name")));
Log.d("Mention Info", "Id : "+obj.getString("id")+" Name : "+obj.getString("name"));
}
}
}
if ( str != null || str.length() != 0) {
// VALID RESPONSE, NOW PARSE IT
if (jsonObj.has("videoUserData")) {
Log.d("# obj=", "" + jsonObj.toString());
Log.d("videoUserData"," "+ jsonObj.getString("videoUserData"));
}
}
if ( str != null || str.length() != 0) {
// VALID RESPONSE, NOW PARSE IT
if (jsonObj.has("friendsAdded")) {
JSONArray colArray = jsonObj.getJSONArray("friendsAdded");
String json = colArray.toString();
Log.d("Colunm Array", ""+colArray);
int nfriendsAdded = colArray.length();
Log.d("# friendsAdded", "" + nfriendsAdded);
for(int i=0; i<nfriendsAdded; i++){
JSONObject obj = colArray.getJSONObject(i);
Log.d("# obj=", "" + obj.toString());
String id = obj.getString("userId");
String name = obj.getString("name");
String imgUrl = obj.getString("imageLink");
db.addCustomer(new FriendListInfo(id, name, imgUrl));
}
}
}
if ( str != null || str.length() != 0) {
// VALID RESPONSE, NOW PARSE IT
if (jsonObj.has("friendsDeleted")) {
JSONArray colArray = jsonObj.getJSONArray("friendsDeleted");
Log.d("Colunm Array", ""+colArray);
int nfriendsDeleted = colArray.length();
Log.d("# friendsDeleted", "" + nfriendsDeleted);
for(int i=0; i<nfriendsDeleted; i++){
JSONObject obj = colArray.getJSONObject(i);
Log.d("# obj=", "" + obj.toString());
}
}else{
Log.d("Delete Friends", " No Deleted List");
}
}
if ( str != null || str.length() != 0) {
// VALID RESPONSE, NOW PARSE IT
if (jsonObj.has("friendsUpdated")) {
JSONArray colArray = jsonObj.getJSONArray("friendsUpdated");
Log.d("Colunm Array", ""+colArray);
int nfriendsUpdated = colArray.length();
Log.d("# friendsDeleted", "" + nfriendsUpdated);
for(int i=0; i<nfriendsUpdated; i++){
JSONObject obj = colArray.getJSONObject(i);
Log.d("# obj=", "" + obj.toString());
}
}else{
Log.d("Update Friends", " No Updated List");
}
}
if ( str != null || str.length() != 0) {
// VALID RESPONSE, NOW PARSE IT
if (jsonObj.has("friendsSyncDate")) {
Log.d("# friendsDeleted", "" + jsonObj);
Log.d("# obj=", "" + jsonObj.toString());
String myString = m_session.getfriendsSyncDate();
Log.d("myString", myString);
m_session.putfriendsSyncDate(jsonObj.getString("friendsSyncDate"));
Log.d("Sync Date "," "+jsonObj.getString("friendsSyncDate"));
}
}
} catch (JSONException je2) {
je2.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Add adapter-listview update code
case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
{
mBuzy = true;
int count = CommentList.getCount();
if(CommentList.getFirstVisiblePosition()==0){
CommentListInfo c;
c = (CommentListInfo) CommentList.getAdapter().getItem(CommentList.getFirstVisiblePosition());
mPositionId = c.CommentId;
Log.d("mpositionId", mPositionId);
String strUrl = GlobalMethod.TokenGenerator() + "&action=getCommentsVideo";
new CommentsDetail().execute(UserId,VidoId,strfriendsSyncDate,c.CommentId,strUrl,"1");
CommentList.setAdapter(commentAdapter); //update code
}

regular-expressions android

i have string like these for example
309\306\308\337_338
309\306\337_338
310
311\315_316\336_337
311\315_316\336_337
311\335_336
these strings means list of page number , for example string "309\306\308\337_339" means
pages 309,306,308,337,338,339
i want to pass one of these string to function which return it as string like this
309,306,308,337,338,339
this function do that but in c# , i want to impalement in android
private static string Get_PageNumbers(string str)
{
ArrayList arrAll = new ArrayList();
MatchCollection match;
string[] excar;
string strid, firstNumber, lastlNumber;
int fn, ln;
ArrayList arrID = new ArrayList();
//***In Case The Range Number Between "_"
if (str.Contains("_"))
{
// match_reg = new Regex("(w?[\\d]+)*(_[\\d]+)");
Regex matchReg = new Regex("(w?[\\69]+_[\\d]+)*(q?[\\d]+//)*(a?[\\d]+_[\\d]+)*(y?[\\d]+)*");
match = matchReg.Matches(str);
int count = match.Count;
excar = new string[0];
for (int i = 0; i < count; i++)
{
Array.Resize(ref excar, count);
excar[i] = match[i].Groups[0].Value;
if (excar[i] != string.Empty)
arrID.Add(excar[i]);
}
//******IF Array Contains Range Of Number Like"102_110"
if (str.Contains("_"))
{
for (int i = 0; i < arrID.Count; i++)
{
strid = arrID[i].ToString();
if (arrID[i].ToString().Contains("_"))
{
int idy = strid.LastIndexOf("_");
firstNumber = strid.Substring(0, idy);
if (idy != -1)
{
lastlNumber = strid.Substring(idy + 1);
fn = int.Parse(firstNumber);
arrAll.Add(fn);
ln = int.Parse(lastlNumber);
for (int c = fn; c < ln; c++)
{
fn++;
arrAll.Add(fn);
}
}
}
else
{
arrAll.Add(arrID[i].ToString());
}
}
//******If Array Contain More Than One Number
if (arrAll.Count > 0)
{
str = "";
for (int i = 0; i < arrAll.Count; i++)
{
if (str != string.Empty)
str = str + "," + arrAll[i];
else
str = arrAll[i].ToString();
}
}
}
}
//***If string Contains between "/" only without "_"
else if (str.Contains("/") && !str.Contains("_"))
{
str = str.Replace("/", ",");
}
else if (str.Contains("\\"))
{
str = str.Replace("\\", ",");
}
return str;
}
I think this is easier to do with split function:
public static String Get_PageNumbers(String str) {// Assume str = "309\\306\\308\\337_338"
String result = "";
String[] pages = str.split("\\\\"); // now we have pages = {"309","306","308","337_338"}
for (int i = 0; i < pages.length; i++) {
String page = pages[i];
int index = page.indexOf('_');
if (index != -1) { // special case i.e. "337_338", index = 3
int start = Integer.parseInt(page.substring(0, index)); // start = 337
int end = Integer.parseInt(page.substring(index + 1)); // end = 338
for (int j = start; j <= end; j++) {
result += String.valueOf(j);
if (j != end) { // don't add ',' after last one
result += ",";
}
}
} else { // regular case i.e. "309","306","308"
result += page;
}
if (i != (pages.length-1)) { // don't add ',' after last one
result += ",";
}
}
return result; // result = "309,306,308,337,338"
}
For example this function when called as follows:
String result1 = Get_PageNumbers("309\\306\\308\\337_338");
String result2 = Get_PageNumbers("311\\315_316\\336_337");
String result3 = Get_PageNumbers("310");
Returns:
309,306,308,337,338
311,315,316,336,337
310
if i can suggest different implementation....
first, split string with "\" str.split("\\");, here you receive an array string with single number or a pattern like "num_num"
for all string founded, if string NOT contains "" char, put string in another array (othArr named), than, you split again with "" str.split("_");, now you have a 2 position array
convert that 2 strings in integer
now create a loot to min val form max val or two strings converted (and put it into othArr)
tranform othArr in a string separated with ","

Android update sqlite table

I have written Update table using dbAdapter.
public void loadDownloadData() {
SoapPrimitive responsePrimitiveData;
//Loop Table list
for (int i = 0; i < tablesName.size(); i++) {
try {
responsePrimitiveData = soapPrimitiveData(tablesName.get(i));
if (responsePrimitiveData != null) {
try {
String result = responsePrimitiveData.toString();
JSONObject jsonobject = new JSONObject(result);
JSONArray array = jsonobject.getJSONArray("Table1");
int max = array.length();
// Loop each table data
for (int j = 0; j < max; j++) {
JSONObject obj = array.getJSONObject(j);
JSONArray names = obj.names();
StringBuilder strFields = new StringBuilder();
StringBuilder strValues = new StringBuilder();
String[] strToFields = new String[names.length()];
String[] strToFieldsVal = new String[names.length()];
//getting the Json name, values in separate string array
for (int k = 0; k < names.length(); k++) {
String name = names.getString(k);
strToFields[k] = names.getString(k);
String strVal;
if(obj.getString(name)== null){
strVal="";
strToFieldsVal[k]="";
}else{
if(obj.getString(name).equals(" ")){
strVal="";
strToFieldsVal[k]="";
}else{
String tmp1 = obj.getString(name).replaceAll("\\s+", " ");
String tmp = tmp1.replaceAll("\\s+", " ");
strVal =tmp.replaceAll("\\s+", " ");
strToFieldsVal[k]=strVal;
}
}
strFields.append(name + ",");
strValues.append(strVal+",");
} //end of json for loop
strFields.deleteCharAt(strFields.length() - 1);
strValues.deleteCharAt(strValues.length() - 1);
if(getTableUpdateType(tablesName.get(i)).equals("1")){
String actualtable = getAndroidTablename(tablesName.get(i));
if(isTableRecords(tablesName.get(i))){
String[] strWhereField = getTablePrimaryKey(tablesName.get(i),strBusinessUnit);
String[] strWhereFieldVal = new String[strWhereField.length];
StringBuilder whereFields = new StringBuilder();
for (int a = 0; a < strWhereField.length; a++) {
strWhereFieldVal[a] = obj.getString(strWhereField[a]);
whereFields.append(strWhereField[a] + "= ? and ");
}
whereFields.delete(whereFields.length() - 4, whereFields.length());
updateTableRecords(actualtable, strToFields, strToFieldsVal,whereFields.toString() ,strWhereFieldVal);
}else{
insertTableRecords(actualtable, strToFields, strToFieldsVal);
}
}else if(getTableUpdateType(tablesName.get(i)).equals("2")){
}else if(getTableUpdateType(tablesName.get(i)).equals("3")){
}else{
}
}//end of each table data
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
}
}
and I called like update method:
public void updateTableRecords(String strTableName, String[] strToFields, String[] strValues,String strWhereField ,String[] strWhereFieldVal){
DBAdapter dbAdapter = DBAdapter.getDBAdapterInstance(DownlaodTableActivity.this);
dbAdapter.openDataBase();
ContentValues initialValues = new ContentValues();
for(int i=0 ;i<strToFields.length;i++){
initialValues.put(strToFields[i],strValues[i]);
}
long n = dbAdapter.updateRecordsInDB(strTableName, initialValues, strWhereField, strWhereFieldVal);
System.out.println( " -- n--- " + n);
Toast.makeText(DownlaodTableActivity.this, n+" rows updated", Toast.LENGTH_SHORT).show();
}
I want to generate update statement dynamic way. From These code I put Where part also.But I did not generate where clause.
see :
UPDATE strTableName SET ExecutiveCode=?, FreeIssuePrefix=?, DisPaySchedulePrefix=?, NextFreeIssueNo=?, NextReturnNo=?, UploadedType=?, DisNextFOCNo=?, DisNextFreeIssueNo=?
Please help me How to give the Where clase(Here I gave String & arguments as string array)
Thanks in advance...
try like this
dbAdapter.updateRecordsInDB(strTableName, initialValues,""+whereField+"='"+whereFieldValue+"'",null);
if your whereField field's type is number then don't use ''
If you have to compare with multiple values use
String where="";
for(int i=0;i<strWhereField.length();i++)
{
where=where+whereField[i]+"='"+strWhereFieldValue[i]+"'"
if(i<(strWhereField.length()-1)) where=where+" and"
}
dbAdapter.updateRecordsInDB(strTableName, initialValues,where,null);

Categories

Resources