Host is unresolved: api.twitter.com:80 - java

I am getting this Error while executing my android application :
Host is unresolved: api.twitter.com:80
Relevant discussions can be on the Internet at:
http://www.google.co.jp/search?q=10f5ada3 or
http://www.google.co.jp/search?q=dceba048
TwitterException{exceptionCode=[10f5ada3-dceba048 10f5ada3-dceba01e], statusCode=-1, retryAfter=-1, rateLimitStatus=null, featureSpecificRateLimitStatus=null, version=2.2.5}
Though i have already set proper permissions.. here is my code :
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.abc"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:label="test1"
android:name=".A1Activity"
android:launchMode="singleTask">
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="twitterapp" android:host="callback" />
</intent-filter>
</activity>
<activity class=".screen2" android:label="test2" android:name=".screen2">
</activity>
</application>
</manifest>
Code for my file is :
public class A1Activity extends Activity {
private static final String PREF_ACCESS_TOKEN = "accessToken"; // Called when the activity is first created.
private static final String PREF_ACCESS_TOKEN_SECRET = "accessTokenSecret";// Name to store the users access token secret
public final static String CONSUMER_KEY = "abc"; // "your key here";
public final static String CONSUMER_SECRET = "def"; // "your secret key here";
private static final String CALLBACK_URL = "twitterapp://callback";// The url that Twitter will redirect to after a user log
private SharedPreferences mPrefs; // Preferences to store a logged in users credentials
private Twitter mTwitter;// = new TwitterFactory().getInstance();
private RequestToken mReqToken;/** The request token signifies the unique ID of the request you are sending to twitter */
public int returnFlag=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mPrefs = getSharedPreferences("twitterPrefs", MODE_PRIVATE);
mTwitter = new TwitterFactory().getInstance();
mTwitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
Button mLoginButton = (Button) findViewById(R.id.login_button);
mLoginButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
System.out.println("1");
loginNewUser();
System.out.println("7.saveAccessToken ");
//Intent screenEnterZip = new Intent(A1Activity.this, screen2.class);
//startActivity(screenEnterZip);// Perform action on click
}
});
}
public void loginNewUser() {
try {
System.out.println("2");
mReqToken = mTwitter.getOAuthRequestToken(CALLBACK_URL);
System.out.println("2.1");
WebView twitterSite = new WebView(this);
System.out.println("2.2");
twitterSite.loadUrl(mReqToken.getAuthenticationURL());
System.out.println("2.3");
setContentView(twitterSite);
//Status status = mTwitter.updateStatus("My First Tweet ... ");
//System.out.println("Successfully updated the status to [" + status.getText() + "].");
System.out.println("1. loginNewUser Completes ");
}
catch (TwitterException e) {
System.out.println("ExceptioniZ "+e);
Toast.makeText(this, "Twitter Login error, try again later", Toast.LENGTH_SHORT).show();
}
}
The app opens in emulator with a screen showing a login button. But on login button click it is throwing regular errors now while the app was working few hours ago...
Can anyone suggest what could have been the problem .. ?

You probably don't have an internet connection in your emulator.
Open up a browser within the emulator and enter "http://api.twitter.com". This probably won't work. Do the same on your local pc it should work there.

Related

App login using Facebook is not working in development! It just loading and Closed- Android Studio

I have implemented an app and I have used facebook login to it. Application is running without crashing but facebook login is not working. When I open up the app and click the facebook login button it will show a progress bar and it will be disappeared immediately without doing anything. I have got the following error in the logcat.
2019-08-29 12:45:24.290 19304-19328/com.appic.testfbauth
E/GraphResponse:
{
HttpStatus: 400,
errorCode: 100,
subErrorCode: 33,
errorType: GraphMethodException,
errorMessage: Unsupported get request. Object with ID '742177629556035' does not exist, cannot be loaded due to missing permissions, or does not support this operation. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api
}
refer below for work I have done.
public class MainActivity extends AppCompatActivity {
private LoginButton loginButton;
private CircleImageView circleImageView;
private TextView txtName, txtEmail;
private CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FacebookSdk.sdkInitialize(getApplicationContext());
loginButton = findViewById(R.id.login_button);
circleImageView = findViewById(R.id.profile_pic);
txtName = findViewById(R.id.profile_name);
txtEmail = findViewById(R.id.profile_email);
checkLoginStatus();
callbackManager = CallbackManager.Factory.create();
loginButton.registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
AccessTokenTracker tokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
if(currentAccessToken == null) {
txtEmail.setText("");
txtName.setText("");
circleImageView.setImageResource(0);
Toast.makeText(MainActivity.this, "User Logged Out!", Toast.LENGTH_SHORT).show();
}
else loadUser(currentAccessToken);
}
};
private void loadUser(AccessToken newAccessToken) {
GraphRequest request = GraphRequest.newMeRequest(newAccessToken, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
String first_name = object.getString("first_name");
String last_name = object.getString("last_name");
String email = object.getString("email");
String id = object.getString("id");
String image_url = "https://graph.facebook.com/"+ id +"/picture?type=normal";
txtEmail.setText(email);
txtName.setText(first_name +" "+ last_name);
RequestOptions requestOptions = new RequestOptions();
requestOptions.dontAnimate();
Glide.with(MainActivity.this).load(image_url).into(circleImageView);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "first_name,last_name,email,id");
request.setParameters(parameters);
request.executeAsync();
}
private void checkLoginStatus() {
if(AccessToken.getCurrentAccessToken() != null) {
loadUser(AccessToken.getCurrentAccessToken());
}
}
}
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data android:name="com.facebook.sdk.ApplicationId"
android:value="#string/facebook_app_id"/>
<meta-data android:name="com.facebook.sdk.ApplicationName"
android:value="#string/app_name"/>
<activity android:name="com.facebook.FacebookActivity"
android:configChanges=
"keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="#string/app_name" />
<activity
android:name="com.facebook.CustomTabActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="#string/fb_login_protocol_scheme" />
</intent-filter>
</activity>
</application>
I just want to integrate the facebook login and get email, name, image url, id.
I have no enough replication for comment so i paste answer. You just give me answers to my below questions.
You test your app in real device or emulator.?
Get the permission for image?
Please check your browser any facebook account already login there?
If you not getting email and name please try below code:
JSONObject res;
res = new JSONObject(json_object.toString());
String id = res.getString("id");
String name = res.getString("name");
String email = res.getString("email");
Update:
Please Uninstalled FB app from your device and try to login with FB in your app it's working fine.
Update 25/11/209
Also please update your hash key - Please follow this answer
After that convert hash key into base 64 - tomeko.net

Insert data from parse into sqllite database

I am trying to get notification content and store it into the database automatically, as soon as the notification is released from parse.com the data should be saved in the database whether the user clicks to view the notification or not.
This is what i have tried so far but still not working. It only save the content into a database when a user clicks on the notification.
Application.java
public class Application extends android.app.Application{
public Application() {
}
#SuppressWarnings("deprecation")
public void onCreate() {
super.onCreate();
// Initialize the Parse SDK.
Parse.initialize(this, "YwWVJ1IdukAXQx6WqksoRlA94k1OoJ6cHqdgsInHaTN", "fCh5pWNiSaHaFtuACufgs9va6wq31pte8nuaiCAG6Nb");
// Specify an Activity to handle all pushes by default.
PushService.setDefaultPushCallback(this, Notification.class);
}
}
FireBackground.java
public class FireBackground extends ParsePushBroadcastReceiver {
#Override
public void onPushOpen(Context context, Intent intent) {
Intent i = new Intent(context, Notification.class);
i.putExtras(intent.getExtras());
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
Notification.java
public class Notification extends ListActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ParseAnalytics.trackAppOpened(getIntent());
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String message="";
SQLiteDatabase db;
db = openOrCreateDatabase(
"notification.db"
, SQLiteDatabase.CREATE_IF_NECESSARY
, null
);
//CREATE TABLES AND INSERT MESSAGES INTO THE TABLES
String CREATE_TABLE_NOTICES = "CREATE TABLE IF NOT EXISTS notices ("
+ "ID INTEGER primary key AUTOINCREMENT,"
+ "NOTIFICATIONS TEXT)";
db.execSQL(CREATE_TABLE_NOTICES);
if(extras !=null){
String jsonData = extras.getString("com.parse.Data");
try{
JSONObject notification = new JSONObject(jsonData);
message = notification.getString("alert");
String sql =
"INSERT or replace INTO notices (NOTIFICATIONS) "
+ "VALUES('" + message + "')";
db.execSQL(sql);
}
catch(JSONException e){
Toast.makeText(getApplicationContext(), "Something went wrong with the notification", Toast.LENGTH_SHORT).show();
}
}
}
android manifest file
<application
android:name="com.parse.starter.Application"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppBaseTheme" >
<activity
android:name="com.parse.starter.Notification"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.parse.PushService" />
<receiver android:name=".HomeActivity"
android:exported="false" >
<intent-filter>
<action android:name="com.parse.push.intent.RECEIVE" />
<action android:name="com.parse.push.intent.DELETE" />
<action android:name="com.parse.push.intent.OPEN" />
</intent-filter>
</receiver>
<receiver android:name="com.parse.ParseBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.USER_PRESENT" />
</intent-filter>
</receiver>
<receiver android:name="com.parse.GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<!--
IMPORTANT: If you change the package name of this sample app,
change "com.parse.starter" in the lines
below to match the new package name.
-->
<category android:name="com.parse.starter" />
</intent-filter>
</receiver>
I would be grateful if anyone would direct me to use the correct method. Thanks
Your code for saving the notification data to your local database runs in the Activity. And the activity is started when the notification is opened, hence the nameonPushOpen. Hence, move the code that saves to the database to FireBackground in a method like onPushRecieved(...)
You should override onPushReceive method in your BroadcastReceiver and than get necessary data
from intent.
Here is my example with retreiving jsonData:
#Override
protected void onPushReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
String jsonData = extras.getString("com.parse.Data");
DBServiceFlow.save(intent);
} catch (JSONException | ParseException e) {
Log.e(TAG, "", e);
}
}
Then you could implement your own Service with background thread to save your data. For example you could just use IntentService
public class DBService extends IntentService {
#Override
public void onHandleIntent(Intent intent) {
if (intent.getAction() == "com.tac.save_notification") {
//parse your json here...
DBHelper.save(...);
}
}
}
PS: never work with DB in main thread. (like you show in your Notification Activity)

Android - Try to send fake sms to myself without mobile network usage

I'm trying to send message to my phone with this app, without using network usage, but my code doesn't work. I followed some tutorial, check android dev and I haven't found anything (in my logcat I don't have error). Could you help me to find out my problem.
My information about compilation, compiler and phone:
Android Studio 1.0.1
API 19 Android 4.4.4 (kitkat)
Build 19
Android phone version 4.4.4
Manifest:
<uses-permission android:name="android.permission.WRITE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
Function of my main activity:
Context context;
String sender;
String body;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Get current context
context = this;
//App started
Toast.makeText(context, "Started", Toast.LENGTH_LONG).show();
CheckApp();
}
private void CheckApp() {
sender = "1234";
body = "Android sms body";
//Get my package name
final String myPackageName = getPackageName();
//Check if my app is the default sms app
if (!Telephony.Sms.getDefaultSmsPackage(this).equals(myPackageName)) {
//Get default sms app
String defaultSmsApp = Telephony.Sms.getDefaultSmsPackage(context);
//Change the default sms app to my app
Intent intent = new Intent( Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, context.getPackageName());
startActivity(intent);
//Write the sms
WriteSms(body, sender);
//Change my sms app to the last default sms app
Intent intent2 = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
intent2.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, defaultSmsApp);
startActivity(intent2);
}
else{
//Write the sms
WriteSms(body, sender);
}
}
//Write the sms
private void WriteSms(String message, String phoneNumber) {
//Put content values
ContentValues values = new ContentValues();
values.put(Telephony.Sms.ADDRESS, phoneNumber);
values.put(Telephony.Sms.DATE, System.currentTimeMillis());
values.put(Telephony.Sms.BODY, message);
//Insert the message
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
context.getContentResolver().insert(Telephony.Sms.Sent.CONTENT_URI, values);
}
else {
context.getContentResolver().insert(Uri.parse("content://sms/sent"), values);
}
}
Well, this is what i wanna do but with my own app and not with the app Fake Text Message that downloaded to the play store.
Make the fake message and what should i see on my default sms app:
With the help from Mike M. I finally finished my program. So, this is the code that you must add to your app to be able to send sms without using network:
Manifest:
<uses-permission android:name="android.permission.WRITE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<!-- BroadcastReceiver that listens for incoming SMS messages -->
<receiver android:name=".SmsReceiver"
android:permission="android.permission.BROADCAST_SMS">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_DELIVER" />
</intent-filter>
</receiver>
<!-- BroadcastReceiver that listens for incoming MMS messages -->
<receiver android:name=".MmsReceiver"
android:permission="android.permission.BROADCAST_WAP_PUSH">
<intent-filter>
<action android:name="android.provider.Telephony.WAP_PUSH_DELIVER" />
<data android:mimeType="application/vnd.wap.mms-message" />
</intent-filter>
</receiver>
<!-- My activity -->
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Activity that allows the user to send new SMS/MMS messages -->
<activity android:name=".ComposeSmsActivity" >
<intent-filter>
<action android:name="android.intent.action.SEND" />
<action android:name="android.intent.action.SENDTO" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="sms" />
<data android:scheme="smsto" />
<data android:scheme="mms" />
<data android:scheme="mmsto" />
</intent-filter>
</activity>
<!-- Service that delivers messages from the phone "quick response" -->
<service android:name=".HeadlessSmsSendService"
android:permission="android.permission.SEND_RESPOND_VIA_MESSAGE"
android:exported="true" >
<intent-filter>
<action android:name="android.intent.action.RESPOND_VIA_MESSAGE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="sms" />
<data android:scheme="smsto" />
<data android:scheme="mms" />
<data android:scheme="mmsto" />
</intent-filter>
</service>
</application>
Main Activity:
Context context;
Button button;
String sender,body,defaultSmsApp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Get current context
context = this;
//Set composant
button = (Button) findViewById(R.id.button);
//Get default sms app
defaultSmsApp = Telephony.Sms.getDefaultSmsPackage(context);
//Set the number and the body for the sms
sender = "0042";
body = "Android fake message";
//Button to write to the default sms app
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Get the package name and check if my app is not the default sms app
final String myPackageName = getPackageName();
if (!Telephony.Sms.getDefaultSmsPackage(context).equals(myPackageName)) {
//Change the default sms app to my app
Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, context.getPackageName());
startActivityForResult(intent, 1);
}
}
});
}
//Write to the default sms app
private void WriteSms(String message, String phoneNumber) {
//Put content values
ContentValues values = new ContentValues();
values.put(Telephony.Sms.ADDRESS, phoneNumber);
values.put(Telephony.Sms.DATE, System.currentTimeMillis());
values.put(Telephony.Sms.BODY, message);
//Insert the message
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
context.getContentResolver().insert(Telephony.Sms.Sent.CONTENT_URI, values);
}
else {
context.getContentResolver().insert(Uri.parse("content://sms/sent"), values);
}
//Change my sms app to the last default sms
Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, defaultSmsApp);
context.startActivity(intent);
}
//Get result from default sms dialog pops up
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
final String myPackageName = getPackageName();
if (Telephony.Sms.getDefaultSmsPackage(context).equals(myPackageName)) {
//Write to the default sms app
WriteSms(body, sender);
}
}
}
}
As a result of adding things in your manifest you must add 4 classes: SmsReceiver, MmsReceiver, ComposeSmsActivity and HeadlessSmsSendService. You can let them empty as shown below.
SmsReceiver:
public class SmsReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
}
}
MmsReceiver:
public class MmsReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
}
}
ComposeSmsActivity:
public class ComposeSmsActivity extends ActionBarActivity {
}
HeadlessSmsSendService:
public class HeadlessSmsSendService extends IntentService {
public HeadlessSmsSendService() {
super(HeadlessSmsSendService.class.getName());
}
#Override
protected void onHandleIntent(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
}
If you need more help to understand this program have a look there:
Youtube - DevBytes: Android 4.4 SMS APIs
Android developers - Getting Your SMS Apps Ready for KitKat
Possiblemobile - KitKat SMS and MMS supports

Can't get GCM register ID client side android

I cant get registration ID for all the devices.
The manifest is good and i add all premission.
the Sender_ID is good.
the device has an account logged in. (Google account).
the code below is the activity which handles with the GCM device register.
Please help me!
public class ClientRegisterActivity extends Activity {
private static final String SENDER_ID = "*******";
private Client client = null;
private GoogleCloudMessaging gcm;
TextView tvHeader;
EditText etEmail;
EditText etPass;
EditText etPassConf;
EditText etFname;
EditText etLname;
EditText etPhone;
// Spinner spWorkArea;
Button bReg;
// Variables used for conversion into database
String fName;
String lName;
String email;
String password;
String phone;
// String workArea;
String regId = "";
String rg;
MyGCMBroadcastReceiver myReci;
// SQLLiteData entry = new SQLLiteData(RegisterActivity.this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.client_activity_register);
initialize();
}
private void initialize() {
tvHeader = (TextView) findViewById(R.id.ctvHeader);
etEmail = (EditText) findViewById(R.id.cemail);
etPass = (EditText) findViewById(R.id.cpassword);
etPassConf = (EditText) findViewById(R.id.cpassword_confirm);
etFname = (EditText) findViewById(R.id.cfirst_name);
etLname = (EditText) findViewById(R.id.clast_name);
etPhone = (EditText) findViewById(R.id.cetPhone);
// spWorkArea = (Spinner) findViewById(R.id.cspWorkArea);
bReg = (Button) findViewById(R.id.cbRegister);
regId="";
// Avoiding NullPointerException in checks
etEmail.setText("");
etPass.setText("");
etPassConf.setText("");
etFname.setText("");
etLname.setText("");
etPhone.setText("");
myReci=new MyGCMBroadcastReceiver();
registerReceiver(myReci,new IntentFilter("com.avshalom.ilani.easymovers.DISPLAY_MESSAGE_ACTION"));
bReg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
boolean didItWork;
registerInBackground();
if (everythingOK()) {
// fName, lName, email, password have been updated in check
// function
// Write details in DB and continue to main screen / show
// confirmation message
if (!regId.equals(null))
didItWork = true;
// not null ?
}
else
setContentView(R.layout.client_activity_register);
Log.d("Text", "kobi: regId = " + regId);
Gson gson = new Gson();
client = new Client();
SendHttpRequest snd = new SendHttpRequest((etFname.getText()
.toString()), etLname.getText().toString(), etEmail
.getText().toString(), etPass.getText().toString(),
etPhone.getText().toString(), regId.toString());
snd.start();
// HttpResponse
// response=SendHttpRequest.SendLogin(etFname.getText().toString(),etLname.getText().toString(),etEmail.getText().toString(),etPass.getText().toString(),etPhone.getText().toString(),
// regId.toString());
Log.d("Text", "kobi: after httpresponse");
// client = gson.fromJson(reader, Client.class);
Toast.makeText(ClientRegisterActivity.this,
client.getFirstName(), 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.register, menu);
return true;
}
private void registerInBackground() {
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
}
// while(regId=="")
rg = gcm.register(SENDER_ID);
regId=rg;
msg = "Device registered, registration ID=" + regId;
System.out.println(msg);
Log.d("Text", msg);
Log.d("Text", "kobi: " + regId);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
#Override
protected void onPostExecute(String msg) {
}
}.execute(null, null, null);
}
register activity after onpreexecute:
bReg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//boolean didItWork;
registerInBackground();
/*
if (everythingOK()) {
// fName, lName, email, password have been updated in check
// function
// Write details in DB and continue to main screen / show
// confirmation message
if (!regId.equals(null))
didItWork = true;
// not null ?
}
else
setContentView(R.layout.client_activity_register); */
Log.d("Text", "kobi: regId = " + regId);
Gson gson = new Gson();
client = new Client();
SendHttpRequest snd = new SendHttpRequest((etFname.getText()
.toString()), etLname.getText().toString(), etEmail
.getText().toString(), etPass.getText().toString(),
etPhone.getText().toString(), regId.toString());
snd.start();
// HttpResponse
// response=SendHttpRequest.SendLogin(etFname.getText().toString(),etLname.getText().toString(),etEmail.getText().toString(),etPass.getText().toString(),etPhone.getText().toString(),
// regId.toString());
Log.d("Text", "kobi: after httpresponse");
// client = gson.fromJson(reader, Client.class);
Toast.makeText(ClientRegisterActivity.this,
client.getFirstName(), 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.register, menu);
return true;
}
private void registerInBackground() {
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
}
// while(regId=="")
rg = gcm.register(SENDER_ID);
regId=rg;
msg = "Device registered, registration ID=" + regId;
System.out.println(msg);
Log.d("Text", msg);
Log.d("Text", "kobi: " + regId);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
#Override
protected void onPostExecute(String msg) {
boolean didItWork;
if (everythingOK()) {
// fName, lName, email, password have been updated in check
// function
// Write details in DB and continue to main screen / show
// confirmation message
if (!regId.equals(null))
didItWork = true;
// not null ?
else
setContentView(R.layout.client_activity_register);
}
}
}.execute(null, null, null);
}
Here is the Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.avshalom.ilani.easymovers"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="17" />
<!-- For receiving messaged from the GCM -->
<permission
android:name="com.avshalom.ilani.easymovers.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.avshalom.ilani.easymovers.permission.C2D_MESSAGE" />
<!-- For receiving messaged from the GCM -->
<!-- For receiving the GCM messages -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<!-- For accessing the internet -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- For google accounts -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<!-- When receiving a message, to keep the device awake -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.avshalom.ilani.easymovers.Login"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.avshalom.ilani.easymovers.Choose"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.avshalom.ilani.easymovers.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.avshalom.ilani.easymovers.ClientRegisterActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.avshalom.ilani.easymovers.offers.tabs"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.avshalom.ilani.easymovers.MoverRegisterActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<receiver
android:name="com.avshalom.ilani.easymovers.MyGCMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.avshalom.ilani.easymovers" />
</intent-filter>
</receiver>
<service android:name="com.avshalom.ilani.easymovers.GCMIntentService" />
</application>
</manifest>

UnknownHostException (webservice http-get)

I have this simple code, that makes a get to a webservice.
For some reason it cant connect and gives the error in the log unknownHostException
This is the code:
String URL = "http://services.sapo.pt/EPG/GetChannelList";
String result = "";
final String tag = "Data received: ";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button btnSearch = (Button)findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
callWebService();
}
});
} // end onCreate()
public void callWebService(){
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet(URL);
ResponseHandler<String> handler = new BasicResponseHandler();
try {
result = httpclient.execute(request, handler);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
httpclient.getConnectionManager().shutdown();
Log.i(tag, result);
}
This is part of my manifest
<permission android:name="android.permission.INTERNET"/>
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".AndroidApp"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
I found the solution.
I putted the internet permission using the GUI in manifest which added the tag
< permission android:name"android.permission.INTERNET"/>
Then by hand, i putted the correct tag that is:
< uses-permission android:name="android.permission.INTERNET" />
which is a different tag and it worked. GUI fail.
Not sure if you have already checked this, but please check if you are behind a proxy or firewall. Here is a way to configure the HttpClient for a proxy and official apache documentation.

Categories

Resources