Hello below is a method where fileUpload method is called and after uploading files i want to delete the synchronized object and i did so. and now i have to reload the page by calling fillRecipients() method, what is does is it lists all the information from the database and shows in the listView. Since i have used the thread it doesnot allow me to put fillRecipeints inside the thread but i want it at line no 230[commented below as Line No 230] below
This is my Synchronize method:
public void synchronize(final String id){
dialog = ProgressDialog.show(ViewRecipients.this, "", "Uploading this file...", true);
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
//uploading.setText("uploading started.....");
//dialog.show();
}
});
mDbHelper.open();
Cursor cData = mDbHelper.fetchRecipientInfo(id);
for(cData.moveToFirst();!cData.isAfterLast();cData.moveToNext()){
String id = cData.getString(cData.getColumnIndex("fld_recipient_id"));
String info = cData.getString(cData.getColumnIndex("fld_info"));
String latitude = cData.getString(cData.getColumnIndex("fld_latitude"));
String longitude = cData.getString(cData.getColumnIndex("fld_longitude"));
ArrayList<String> imagesArray = new ArrayList<String>();
for (int i = 1; i <= 4; i++) {
String image = cData.getString(cData.getColumnIndex("fld_image_url" + i));
if (image != null) {
imagesArray.add(image);
}
}
try {
serverResponseCode = uploadFile(imagesArray, info, latitude, longitude, id);
if (serverResponseCode==200){
mDbHelper.deleteRecipientRecId(id);
//Line NO 230 here i want to add fillRecipients() method
}
dialog.dismiss();
} catch (IOException e) {
e.printStackTrace();
dialog.dismiss();
}
}
cData.close();
mDbHelper.close();
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(ViewRecipients.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
}
});
}
}
}).start();
}
This is my fillRecipeints() method:
private void fillRecipients(){
mCursor = mDbHelper.fetchAllRecipientsInfo();
if (mCursor==null){
System.out.println("empty cursor");
}
else{
String [] from = new String[]{MunchaDbAdapter.FLD_RECIPIENT_ID};
int [] to = new int[]{R.id.text1};
SimpleCursorAdapter recipient = new SimpleCursorAdapter(this, R.layout.recipient_show, mCursor, from, to);
setListAdapter(recipient);
}
}
can any body help me?
public void synchronize(final String id) {
new UploadAsync.execute();
}
//async class to do task in background and notify UI after completion of task in onPost()
class UploadAsync extends AsyncTask<Void, Void, Void>{
ProgressDialog dialog = null;
boolean isUploaded = false;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
ProgressDialog.show(ViewRecipients.this, "", "Uploading this file...", true);
}
#Override
protected Void doInBackground(Void... params) {
try{
mDbHelper.open();
Cursor cData = mDbHelper.fetchRecipientInfo(id);
for(cData.moveToFirst();!cData.isAfterLast();cData.moveToNext()){
String id = cData.getString(cData.getColumnIndex("fld_recipient_id"));
String info = cData.getString(cData.getColumnIndex("fld_info"));
String latitude = cData.getString(cData.getColumnIndex("fld_latitude"));
String longitude = cData.getString(cData.getColumnIndex("fld_longitude"));
ArrayList<String> imagesArray = new ArrayList<String>();
for (int i = 1; i <= 4; i++) {
String image = cData.getString(cData.getColumnIndex("fld_image_url" + i));
if (image != null) {
imagesArray.add(image);
}
}
try {
serverResponseCode = uploadFile(imagesArray, info, latitude, longitude, id);
if (serverResponseCode==200){
mDbHelper.deleteRecipientRecId(id);
isUploaded = true;
}
} catch (IOException e) {
e.printStackTrace();
}
}
cData.close();
mDbHelper.close();
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//close dialog
if(dialog != null && dialog.isShowing()){
dialog.dismiss();
}
if(isUploaded){
Toast.makeText(ViewRecipients.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
fillRecipients();
}
}
}
private void fillRecipients() {
mCursor = mDbHelper.fetchAllRecipientsInfo();
if (mCursor == null) {
System.out.println("empty cursor");
} else {
String[] from = new String[] { MunchaDbAdapter.FLD_RECIPIENT_ID };
int[] to = new int[] { R.id.text1 };
SimpleCursorAdapter recipient = new SimpleCursorAdapter(this,
R.layout.recipient_show, mCursor, from, to);
setListAdapter(recipient);
}
}
Related
I'm Having difficulty populating TextViews from my SQL Database. I have one column populating a spinner and then I want the Two Textviews to be populated by MySQL Columns from the same row of the spinner selection.
I cannot find the correct code to add to the OnSelectedItem portion.
MainActivity.java
public class MainActivity extends AppCompatActivity implements OnItemSelectedListener{
Context c;
TextView colorDensity;
Spinner colorSpinner= findViewById(R.id.colorSpinner);
ArrayList<String> colors=new ArrayList<>();
final static String urlAddress = "http://www.burtkuntzhandjobs.org/dbcolors.php";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Downloader(MainActivity.this,urlAddress,colorSpinner).execute();
colorDensity = (TextView)findViewById(R.id.colorDensity);
colorSpinner.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(this,"Select Color", Toast.LENGTH_SHORT).show();
}
}
DataParser.java
public class DataParser extends AsyncTask<Void,Void,Integer> {
Context c;
Spinner colorSpinner;
String jsonData;
ProgressDialog pd;
ArrayList<String> colors=new ArrayList<>();
public DataParser(Context c, Spinner colorSpinner, String jsonData) {
this.c = c;
this.colorSpinner = colorSpinner;
this.jsonData = jsonData;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("Parse");
pd.setMessage("Parsing");
pd.show();
}
#Override
protected Integer doInBackground(Void...params) {
return this.parseData();
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
pd.dismiss();
if(result == 0){
Toast.makeText(c,"Unable to Parse",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(c,"Parse Successful",Toast.LENGTH_SHORT).show();
ArrayAdapter adapter = new ArrayAdapter(c,android.R.layout.simple_list_item_1,colors);
colorSpinner.setAdapter(adapter);
}
}
private int parseData() {
try {
JSONArray ja=new JSONArray(jsonData);
JSONObject jo=null;
colors.clear();
Colors s=null;
for (int i = 0; i < ja.length(); i++) {
jo = ja.getJSONObject(i);
int ui = jo.getInt("ui");
String color=jo.getString("color");
String density = jo.getString("density");
String strainer = jo.getString("strainer");
s = new Colors();
s.setIu(ui);
s.setColor(color);
s.setDensity(density);
s.setStrainer(strainer);
colors.add(color);
}
return 3;
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
}
Downloader.java
public class Downloader extends AsyncTask<Void,Void,String> {
Context c;
String urlAddress;
Spinner colorSpinner;
ProgressDialog pd;
public Downloader(Context c, String urlAddress, Spinner colorSpinner) {
this.c = c;
this.urlAddress = urlAddress;
this.colorSpinner = colorSpinner;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("Fetch");
pd.setMessage("Fetching");
pd.show();
}
#Override
protected String doInBackground(Void...params) {
return this.downloadData();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
pd.dismiss();
if(s == null) {
Toast.makeText(c,"Unable to Retrieve",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(c,"Success",Toast.LENGTH_SHORT).show();
DataParser parser=new DataParser(c,colorSpinner,s);
parser.execute();
}
}
private String downloadData() {
HttpURLConnection con= (HttpURLConnection) Connector.connect(urlAddress);
if(con == null) {
return null;
}
InputStream is = null;
try {
is = new BufferedInputStream(con.getInputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String line = null;
StringBuffer response=new StringBuffer();
if(br != null){
while ((line=br.readLine()) !=null) {
response.append(line+"\n");
}
br.close();
} else {
return null;
}
return response.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(is != null){
try{
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}
Make following changes & add required code,
1. Remove Spinner colorSpinner= findViewById(R.id.colorSpinner); from class variable.
2. Add Spinner colorSpinner= findViewById(R.id.colorSpinner); in onCreate` method.
Look this spinet,
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spinner);
Spinner colorSpinner= findViewById(R.id.colorSpinner);
new Downloader(this, urlAddress,colorSpinner).execute();
colorDensity = (TextView)findViewById(R.id.colorDensity);
colorSpinner.setOnItemSelectedListener(this);
}
3. Access colors list from DataParser class,
public class DataParser extends AsyncTask<Void,Void,Integer> {
Context c;
Spinner colorSpinner;
String jsonData;
ProgressDialog pd;
ArrayList<String> colors=new ArrayList<>();
private static ArrayList<Colors> colorsList=new ArrayList<>(); // add this line
public DataParser(Context c, Spinner colorSpinner, String jsonData) {
this.c = c;
this.colorSpinner = colorSpinner;
this.jsonData = jsonData;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("Parse");
pd.setMessage("Parsing");
pd.show();
}
#Override
protected Integer doInBackground(Void...params) {
return this.parseData();
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
pd.dismiss();
if(result == 0){
Toast.makeText(c,"Unable to Parse",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(c,"Parse Successful",Toast.LENGTH_SHORT).show();
ArrayAdapter adapter = new ArrayAdapter(c,android.R.layout.simple_list_item_1,colors);
colorSpinner.setAdapter(adapter);
}
}
private int parseData() {
try {
JSONArray ja=new JSONArray(jsonData);
JSONObject jo=null;
colors.clear();
Colors s=null;
for (int i = 0; i < ja.length(); i++) {
jo = ja.getJSONObject(i);
int ui = jo.getInt("ui");
String color=jo.getString("color");
String density = jo.getString("density");
String strainer = jo.getString("strainer");
s = new Colors();
s.setUi(ui);
s.setColor(color);
s.setDensity(density);
s.setStrainer(strainer);
colors.add(color);
colorsList.add(s); // add this line
}
return 3;
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
public static List<Colors> getColorsList() { // add this method
return colorsList;
}
}
4. Set density accordingly in onItemSelected() method of activity class.
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
List<Colors> colorsList = DataParser.getColorsList();
colorDensity.setText(colorsList.get(position).getDensity());
}
I have an issue with my app when retrieving data from array.
SchedulePage:
public class SchedulePage extends Activity {
List<MyTask> tasks;
List<Test_Sched> SchedList;
// Intent intent = getIntent();
// String Username = intent.getStringExtra("Username2");
int Count = 0;
String SendCount = "";
TextView endtv, durationtv;
//storage of Test_Name
private static ArrayList<String> Test_Name = new ArrayList<String>();
//storage of x values in array private
private static ArrayList<Integer> Duration = new ArrayList<Integer>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_schedule_page);
endtv = (TextView) findViewById(R.id.Endtv);
durationtv = (TextView) findViewById(R.id.Durationtv);
//Use this to Create Layouts Dynamically
//RelativeLayout relativeLayout = new RelativeLayout(this);
tasks = new ArrayList<>();
GetSchedule();
//GridView gv = (GridView) findViewById(R.id.grid);
//gv.setAdapter(new ImageAdapter(getApplicationContext()));
//Storing test name Arraylist in a array
final String [] web = Test_Name.toArray(new String[Test_Name.size()]);
//Storing images in a array
ArrayList<Integer> imagesAL = new ArrayList<Integer>();
for(int i = 0; i < Test_Name.size(); i++){
// String testname = web[i];
String lf = "One Leg(Left)", rf = "One Leg(Right)", sf = "Separate Foot", sbsf= "Side By Side Foot", tthr ="Toe To Heel(Right)", tthl ="Toe To Heel(Left)";
if(lf.equals(Test_Name.get(i))){
imagesAL.add(R.drawable.leftfoot);
}
if(rf.equals(Test_Name.get(i))){
imagesAL.add(R.drawable.rightfoot);
}
if(sf.equals(Test_Name.get(i))){
imagesAL.add(R.drawable.feetapart);
}
if(sbsf.equals(Test_Name.get(i))){
imagesAL.add(R.drawable.sidebysidefoot);
}
if(tthr.equals(Test_Name.get(i))){
imagesAL.add(R.drawable.righttoetoleftheel);
}
if(tthl.equals(Test_Name.get(i))){
imagesAL.add(R.drawable.lefttoetorightheel);
}
}
Integer [] imageId = imagesAL.toArray(new Integer[imagesAL.size()]);
ImageAdapter adapter = new ImageAdapter(SchedulePage.this, web, imageId);
GridView grid;
grid=(GridView)findViewById(R.id.grid);
grid.setAdapter(adapter);
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(SchedulePage.this, "You Clicked at " +web[+ position], Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.schedule_page, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
//Login Stuff
public static ArrayList<Integer> getDuration() {
return Duration;
}
public static ArrayList<String> getTestName() {
return Test_Name;
}
private void GetSchedule(){
String jsonOutput = "http://172.20.34.112/IBBTS_WebService_MobileAndDevice/Service1.asmx/GetSchedule";
if (isOnline()) {
//while(End == "not yet"){
requestData(jsonOutput);
//}
}else {
Toast.makeText(SchedulePage.this, "Network isn't available", Toast.LENGTH_LONG).show();
}
}
private static String doJSONHTTPCall(String urlStr) {
String output2 = "";
try {
URL url;
try {
url = new URL(urlStr);
}
catch (MalformedURLException e) {
throw e;
}
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
while ((output = br.readLine()) != null) {
output2 += output;
}
conn.disconnect();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return output2;
}
private void requestData(String uri) {
//Send the integer to String
Bundle gt=getIntent().getExtras();
String usernamePass =gt.getString("userName2");
SendCount = Integer.toString(Count);
RequestPackage p = new RequestPackage();
p.setMethod("GET");
p.setUri(uri);
p.setParam("Username", usernamePass);
MyTask task = new MyTask();
task.execute(p);
}
protected void updateDisplay(){
if (SchedList != null) {
for (Test_Sched test_Sched : SchedList) {
Duration.add(test_Sched.getDuration());
Test_Name.add(test_Sched.getTest_Name());
Count++;
}
}
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
private class MyTask extends AsyncTask<RequestPackage, String, String>{
#Override
protected void onPreExecute() {
//updateDisplay("Starting Task");
if (tasks.size() == 0) {
//progress.setVisibility(View.VISIBLE);
}
tasks.add(this);
}
#Override
protected String doInBackground(RequestPackage... params) {
String content = HttpManager.getData(params[0]);
return content;
}
#Override
protected void onPostExecute(String result) {
SchedList = ScheduleJSONParser.parseFeed(result);
updateDisplay();
tasks.remove(this);
if (tasks.size() == 0) {
//progress.setVisibility(View.INVISIBLE);
}
}
#Override
protected void onProgressUpdate(String... values) {
//updateDisplay(values[0]);
}
}
}
ScheduleJSONParsor
public class ScheduleJSONParser {
public static List<Test_Sched> parseFeed(String content) {
try {
JSONArray ar = new JSONArray(content);
List<Test_Sched> SchedList = new ArrayList<>();
for (int i = 0; i < ar.length(); i++) {
JSONObject obj = ar.getJSONObject(i);
Test_Sched test_Sched = new Test_Sched();
test_Sched.setDuration(Integer.parseInt(obj.getString("Duration")));
test_Sched.setTest_Name(obj.getString("Test_Name"));
SchedList.add(test_Sched);
}
return SchedList;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}}
The logcat does not indicate which line has the error and I find it difficult to troubleshoot.
The idea is that it retrieves the schedule from the database and pass it to an array. then the app will display image buttons for each of the exercise name.
Also when I click the schedulePage button from the main menu, it shows up blank and I have to re-click the schedulePage the second time. The second time shows the arrayoutofbounds error..
any help would be appreciated.
The reason is this both lines
GetSchedule();
final String [] web = Test_Name.toArray(new String[Test_Name.size()]);
in GetSChedule() you are running thread in background and from response of webservice you are filling Test_Name array. But before calling webservice you are copying Test_Name data to web array, so your web[] will be blank because there is no data in Test_Name.
Make web[] global
String [] web;
fill it in updateDisplay()
protected void updateDisplay(){
if (SchedList != null) {
for (Test_Sched test_Sched : SchedList) {
Duration.add(test_Sched.getDuration());
Test_Name.add(test_Sched.getTest_Name());
Count++;
}
web = Test_Name.toArray(new String[Test_Name.size()]);
}
}
I want to be when there is incoming sms whose number is not in contact, then the text in the block, for sure by checking whether there are any number is not in the phone book.
i am have a code check number exist, but error time i code move in class BroadcastReceiver?, and how to call method contactExists in onReceive?
public boolean contactExists(Context context, String number, ContentResolver contentResolver) {
Cursor phones = contentResolver.query(ContactsContract.CommonDataKinds.Phone.
CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
while (phones.moveToNext()){
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if(PhoneNumberUtils.compare(number, phoneNumber)){
return true;
}
}
return false;
}
I use AsyncTask, but I am confused about what to call the method contactExists, and how do I enter the number into contactExists, in order to recognize that the number of existing
public class SmsReceiver extends BroadcastReceiver {
public static int MSG_TPE = 0;
private String number;
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(AppConstants.SMS_RECEIVED_ACTION)) {
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String message = "";
String date = AppUtils.getDate();
String time = AppUtils.getTime();
String status = AppUtils.getStatus();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i = 0; i < msgs.length; i++) {
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
number = msgs[i].getOriginatingAddress();
message += msgs[i].getMessageBody().toString();
message += "\n";
}
if (SettingsPreferences.isBlockAllSms(context)) {
this.abortBroadcast();
CallMessageItem item = new CallMessageItem();
item.setDate(date);
item.setMessage(message);
item.setNumber(number);
item.setTime(time);
item.setStatus(status);
item.setType(AppConstants.TYPE_MESSAGE);
CMBDataProvider.addCallMessage(context, item);
if (SettingsPreferences.isNotificationShow(context)) {
AppUtils.generateNotification(
context,
context.getResources().getString(
R.string.block_sms_message), false);
}
} else if (SettingsPreferences.isBlockPrivateSms(context)) {
ArrayList<BlockItem> block_number = CMBDataProvider
.getBlackList(context);
if (!TextUtils.isEmpty(message)
&& !TextUtils.isEmpty(number)
&& block_number != null && block_number.size() > 0) {
message = message.trim();
for (int i = 0; i < block_number.size(); i++) {
if (number
.contains(block_number.get(i).getNumber())) {
this.abortBroadcast();
CallMessageItem item = new CallMessageItem();
item.setDate(date);
item.setMessage(message);
item.setNumber(number);
item.setTime(time);
item.setType(AppConstants.TYPE_MESSAGE);
CMBDataProvider.addCallMessage(context, item);
if (SettingsPreferences
.isNotificationShow(context)) {
AppUtils.generateNotification(
context,
context.getResources().getString(
R.string.block_sms_message),
false);
}
break;
}
}
}
}
}
}
}
private class Contactexixt extends AsyncTask<String, Integer, Double> {
#Override
protected Double doInBackground(String... params) {
// TODO Auto-generated method stub
contactExists(params[0]);
return null;
}
public boolean contactExists(Context context, String number){
Uri lookupUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
String[] mPhoneNumberProjection = { ContactsContract.PhoneLookup._ID, ContactsContract.PhoneLookup.NUMBER, ContactsContract.PhoneLookup.DISPLAY_NAME };
Cursor cur = context.getContentResolver().query(lookupUri,mPhoneNumberProjection, null, null, null);
try {
// Add your data
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
}
Do not query content provider in main thread, run a new thread or use AsyncTask.
private class Checkcontact extends AsyncTask<String, Void, Boolean> {
private Context context;
public Checkcontact(Context context) {
// TODO Auto-generated constructor stub
this.context = context;
}
#Override
protected Boolean doInBackground(String... strings) {
try {
return contactExists(context, strings[0]);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
// The argument result is return by method doInBackground
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// You can handle the result here
}
public boolean contactExists(Context context, String number) throws Exception {
Uri lookupUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
String[] mPhoneNumberProjection = { ContactsContract.PhoneLookup._ID, ContactsContract.PhoneLookup.NUMBER,
ContactsContract.PhoneLookup.DISPLAY_NAME };
Cursor cur = context.getContentResolver().query(lookupUri, mPhoneNumberProjection, null, null, null);
try {
if (cur.moveToFirst()) {
// if contact are in contact list it will return true
return true;
}
} finally {
if (cur != null)
cur.close();
}
// if contact are not match that means contact are not added
return false;
}
}
Start a task:
new Checkcontact(context).execute("123456789");
So i have a registration Android app that in main activity creates a socket connection on create opensocket(). Everything runs perfectly on the first submit, the debugger out put looks great and it sends/recieves data back from my WPF app. Now It goes to a thanks activity which onclick leads back to my mainactivity. Now when i hit submit, it works fine, but is showing its hitting my socket methods twice (only inserts the records once on my WPF app) , and so on as many times i submit. I realize i'm not closing or reusing my socket connection correctly?! I've tried several things, but can't seem to get this to either reuse the same opensocket instance or can't just close and reopen on reload. I'm quite new to android and sockets all together, any help is greatly appreciated!
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
settingsCheck();
openSocket();
sett.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
launchSettings();
}
});
mainLogo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
RefreshMain();
}
});
btn_register.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
tv_errors.setText("");
errorMsg = "";
nameCheck(et_lName.getText().toString(),et_fName.getText().toString());
emailCheck(et_email.getText().toString());
partnerCheck();
mobileCheck(et_mobile.getText().toString());
if (SocketHandler.SocketConnected){
if(errorMsg == ""){
//tv_errors.setText("");
if(checkForSD() == true){
sendRegistrantInfo(et_fName.getText() + "," + et_lName.getText() + "," + et_email.getText() + "," + et_mobile.getText() + "," + et_partEmail.getText() + "," + cb_terms1.isChecked() + "," + cb_terms2.isChecked() );
}
else{
tv_errors.setText("**Please insert an SD Card.");
}
}
else{
//tv_errors.setText(errorMsg);
}
}
else
{
connectionStatus.setText("Connection Error.");
tv_errors.setText("**Connection lost, please try again.");
//openSocket();
}
}
});
}
public void RefreshMain()
{
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
public void launchLogin()
{
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
}//end launchLogin
public void launchSettings()
{
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
}//end launchSettings
public void settingsCheck()
{
SharedPreferences settings = getSharedPreferences("prefs",MODE_PRIVATE);
String currentIP = settings.getString("IPSetting", "");
String currentPort = settings.getString("PORTSetting", "");
currentMem = settings.getString("SDSize", "");
if (currentIP == "" || currentPort == ""){
Intent myIntent = new Intent(this,SettingsActivity.class);
startActivity(myIntent);
}
}//end settingsCheck()
public void launchRingDialog(String id) {
final String idYo = id;
final ProgressDialog ringProgressDialog = ProgressDialog.show(MainActivity.this, "Formatting SD Card","Formatting SD Card, please wait this could take several minutes...", true);
new Thread(new Runnable() {
#Override
public void run() {
try {
fileToSD(idYo);
Thread.sleep(10000);
} catch (Exception e) {
}
ringProgressDialog.dismiss();
}
}).start();
}
public boolean checkForSD()
{
String root = "/storage/removable/sdcard1/";
double memInGigs = round(sizeMatters(root),2);
if(memInGigs >0){
return true;
}
else
{
return false;
}
}
private double sizeMatters(String path)
{
StatFs stat = new StatFs(path);
double availSize = (double)stat.getAvailableBlocks() * (double)stat.getBlockSize();
double ingigs = availSize/ 1073741824;
return ingigs;
}//end sizeMatters()
private void sendRegistrantInfo(String reg){
_sh.sendMessage(reg);
}
private void openSocket(){
_sh = new SocketHandler();
_sh.setSocketHandlerListener(this);
SharedPreferences settings = getSharedPreferences("prefs",MODE_PRIVATE);
String currentIP = settings.getString("IPSetting", "");
String currentPort = settings.getString("PORTSetting", "");
_sh.open(currentIP, currentPort);
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onSocketConnected() {
Log.v(TAG, "onSocketConnected");
connectionStatus.setText("CONNECTED");
}
#Override
public void onSocketData(String msg) {
Log.v(TAG, "onSocketData - " + msg );
int usrID = Integer.parseInt(msg.trim());
if (msg != null & usrID > 0){
launchRingDialog(msg);
Intent intent = new Intent(this, ThanksActivity.class);
startActivity(intent);
}
else if(msg.trim().equals("-2") == true)
{
tv_errors.setText("**This email has already been registered for this event, please click Already Registered button to sign in.");
}
else{
tv_errors.setText("**Error, Please try submitting again.");
errorMsg = "-1";
}
}
#Override
public void onSocketDisconnected() {
Log.v(TAG, "onSocketDisconnected");
connectionStatus.setText("DISCONNECTED");
}
public class SocketHandler {
Socket sc;
public static boolean SocketConnected = false;
private static ClientThread cThread;
public String prefsFile = "prefs";
public String port = "8888";
public String ip = "192.168.1.4";
private String TAG = "SocketHandler";
protected SocketHandlerListener socketHandlerListener;
public interface SocketHandlerListener{
public void onSocketConnected();
public void onSocketData(String msg);
public void onSocketDisconnected();
}
public SocketHandler(){
}
public void setSocketHandlerListener(SocketHandlerListener shl){
socketHandlerListener = shl;
}
public void open(String ip, String port){
this.ip = ip;
this.port = port;
cThread = new ClientThread();
try{
cThread.start();
}catch (Exception ex){
Log.v(TAG, "Error connecting to socket");
}
}
public void close(){
if (cThread != null){
if (cThread.socket != null){
try {
cThread.socket.close();
} catch (Exception e) {
Log.v(TAG, "Error closing socket");
}
cThread.socket = null;
}
}
}
public void sendMessage(String msg){
cThread.sendMessage(msg);
}
public void messageRecieved(String msg){
dispatchSocketData(msg);
}
private void dispatchSocketConnected(){
if (socketHandlerListener != null){
socketHandlerListener.onSocketConnected();
}
}
private void dispatchSocketDisconnected(){
if (socketHandlerListener != null){
socketHandlerListener.onSocketDisconnected();
}
}
private void dispatchSocketData(String msg){
if (socketHandlerListener != null){
socketHandlerListener.onSocketData(msg);
}
}
public class ClientThread extends Thread {
public Socket socket;
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(ip);
Log.v(TAG, "C: Connecting..." + ip + ":" + port);
socket = new Socket(serverAddr, Integer.parseInt(port));
socket.setSoTimeout(0);
socket.setKeepAlive(true);
SocketConnected = true;
handler.post(new Runnable() {
#Override
public void run() {
dispatchSocketConnected();
}
});
// BLOCKING THE THREAD
while (SocketConnected) {
InputStream in = socket.getInputStream();
byte[] buffer = new byte[4096];
int line = in.read(buffer, 0, 4096);
while (line != -1) {
byte[] tempdata = new byte[line];
System.arraycopy(buffer, 0, tempdata, 0, line);
final String data = new String(tempdata);
handler.post(new Runnable() {
#Override
public void run() {
messageRecieved(data);
SocketConnected = false;
}
});
line = in.read(buffer, 0, 4096);
}
// break;
}
socket.close();
Log.v("Socket", "C: Closed.");
handler.post(new Runnable() {
#Override
public void run() {
dispatchSocketDisconnected();
}
});
SocketConnected = false;
} catch (Exception e) {
Log.v("Socket", "C: Error", e);
handler.post(new Runnable() {
#Override
public void run() {
dispatchSocketDisconnected();
}
});
SocketConnected = false;
}
}
Handler handler = new Handler();
public void sendMessage(String msg){
if (socket != null){
if (socket.isConnected()){
PrintWriter out;
try {
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), false);
out.print(msg);
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
I tried this: when isSessionValid getDetails directly else facebook.authorize and then getDetails in onActivityResult
public class MainActivity extends Activity {
Facebook facebook = new Facebook("xxxxxxxxxxxxxxxx");
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
private SharedPreferences mPrefs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
facebook.setAccessToken(access_token);
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this, new String[] {}, new DialogListener() {
#Override
public void onComplete(Bundle values) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token", facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
}
#Override
public void onFacebookError(FacebookError error) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onCancel() {
}
});
}else{
try {
JSONObject json = Util.parseJson(facebook.request("me"));
String facebookID = json.getString("id");
String firstName = json.getString("first_name");
String lastName = json.getString("last_name");
String email = json.getString("email");
String gender = json.getString("gender");
} catch (Exception e) {
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
try {
JSONObject json = Util.parseJson(facebook.request("me"));
String facebookID = json.getString("id");
String firstName = json.getString("first_name");
String lastName = json.getString("last_name");
String email = json.getString("email");
String gender = json.getString("gender");
} catch (Exception e) {
}
}
public void onResume() {
super.onResume();
facebook.extendAccessTokenIfNeeded(this, null);
}
}
This works fine when I have facebook app installed on my system. But If not installed i get a Web View to enter facebook credentials and in logcat shows login-success, but none of the getDetails block is called.
Here in initFacebook() function through you can login and perform you functionality, here i am fetching user's friends information.
private void initFacebook()
{
try
{
if (APP_ID == null)
{
Util.showAlert(this,"Warning","Facebook Applicaton ID must be "+ "specified before running this example: see Example.java");
}
mFacebook = new Facebook();
mAsyncRunner = new AsyncFacebookRunner(mFacebook);
mFacebook.authorize(FacebookList.this, APP_ID, new String[] {"email", "read_stream", "user_hometown", "user_location","friends_about_me", "friends_hometown", "friends_location","user_relationships", "friends_relationship_details","friends_birthday", "friends_education_history","friends_website" }, new DialogListener()
{
public void onComplete(Bundle values)
{
getHTTPConnection();
}
public void onFacebookError(FacebookError error)
{
Log.i("public void onFacebookError(FacebookError error)....","....");
}
public void onError(DialogError e)
{
Log.i("public void onError(DialogError e)....", "....");
CustomConfirmOkDialog dialog = new CustomConfirmOkDialog(FacebookList.this, R.style.CustomDialogTheme, Utils.FACEBOOK_CONNECTION_ERROR);
dialog.show();
}
public void onCancel()
{
Log.i("public void onCancel()....", "....");
}
});
SessionStore.restore(mFacebook, this);
SessionEvents.addAuthListener(new SampleAuthListener());
SessionEvents.addLogoutListener(new SampleLogoutListener());
}
catch (Exception e)
{
e.printStackTrace();
}
}
Here in getHTTPConnection(), proceeding for connection and sending fields, that we require about user's friends as here we can see that passing fields are fields=id,first_name,last_name,location,picture of friends. here you can change this fields according to application's requirements.
private void getHTTPConnection()
{
try
{
mAccessToken = mFacebook.getAccessToken();
HttpClient httpclient = new DefaultHttpClient();
String result = null;
HttpGet httpget = new HttpGet("https://graph.facebook.com/me/friends?access_token="+ mAccessToken + "&fields=id,first_name,last_name,location,picture");
HttpResponse response;
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null)
{
result = EntityUtils.toString(entity);
parseJSON(result);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
Now after successfully connecting with facebook , we are getting JSON data and further to parse it .
private void parseJSON(String data1) throws Exception,NullPointerException, JSONException
{
try
{
JSONObject jObj = new JSONObject(data1);
JSONArray jObjArr = jObj.optJSONArray("data");
int lon = jObjArr.length();
for (int i = 0; i < lon; i++)
{
JSONObject tmp = jObjArr.optJSONObject(i);
String temp_image = tmp.getString("picture"); String temp_fname = tmp.getString("first_name");
String temp_lname = tmp.getString("last_name");
String temp_loc = null;
JSONObject loc = tmp.getJSONObject("location");
temp_loc = loc.getString("name");
}
}
catch (Exception e)
{
Log.i("Exception1 is Here>> ", e.toString());
e.printStackTrace();
}
}
It is assumed that you have already added a facebook jar in to your application and for proceeding this code you can call initFacebook() in to onCreate() of your activity