UnknownHostException (webservice http-get) - java

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.

Related

No auth token firebase storage android

I am sending images to firebase. but when my upload pictures method starts running, I get no auth token printed into my logcat couple of times. I tried using both camera and gallery, but they both make the same output even though my firebase storage rules are:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write;
}
}
}
And my code is:
if (fragment3.isAdded()) {
EditText plantdetails = (EditText) fragment3.getView().findViewById(R.id.plantdetails);
if (plantdetails.getText().toString().equals("")) {
Toast.makeText(newPlant.this, "I think you forgot something.", Toast.LENGTH_LONG).show();
} else {
plants plantss = new plants();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(newPlant.this);
prefs.edit().putString("pldetails", plantdetails.getText().toString()).apply();
String pname = prefs.getString("plname","null");
String pdate = prefs.getString("pldate","null");
String petails = prefs.getString("pldetails","null");
plantss.setPlname(pname);
plantss.setPldate(pdate);
plantss.setPldetails(petails);
reference.child("Plants").child(pname).setValue(plantss);
try {
Fileuploader();
}catch (FileNotFoundException e){
e.printStackTrace();
}
}
}
if (fragment4.isAdded()){
}
}
});
}
private void Fileuploader() throws FileNotFoundException {
String imageid;
progress.showProgress(newPlant.this,"Loading...",false);
DatabaseHelper databaseHelper = new DatabaseHelper(newPlant.this);
Cursor getimage = databaseHelper.GetPath();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(newPlant.this);
String plname = prefs.getString("plname","null");
int count = 0;
int count2 = 0;
if (getimage !=null){
while (getimage.moveToNext()) {
System.out.println("IMAGE IS THIS MY MAN: "+ getimage.getString(0));
Bitmap bm = BitmapFactory.decodeFile(getimage.getString(0));
if (bm == null){
return;
}else {
ByteArrayOutputStream out = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 35, out);
imageid = System.currentTimeMillis() + "_" + (count++) + "." + getExtension(uri);
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Plants").child(plname).child("PlantImages");
String imagekey = reference.push().getKey();
reference.child(imagekey).child("ImageID").setValue(imageid);
reference.child(imagekey).child("ID").setValue(count2++);
System.out.println("IMAGES UPLOADEDDDD: " + imageid);
byte[] data = out.toByteArray();
StorageReference Ref = mStorageRef.child(imageid);
Ref.putBytes(data)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Get a URL to the uploaded content
//Uri downloadUrl = taskSnapshot.getDownloadUrl();
//Toast.makeText(profuctadd.this,"Image uploaded",Toast.LENGTH_LONG).show();
progress.hideProgress();
Intent intent = new Intent(newPlant.this, Donenewplant.class);
startActivity(intent);
finish();
DatabaseHelper mDatabaseHelper = new DatabaseHelper(newPlant.this);
Cursor cursor2 = mDatabaseHelper.DeleteDataOfTableImagesAr();
cursor2.moveToNext();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
Toast.makeText(newPlant.this, "Failed", Toast.LENGTH_LONG).show();
System.out.println("FAILED:::: "+exception);
}
});
}
}
}
}
Mainfest file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.varroxsystems.plant">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#drawable/plant"
android:label="#string/app_name"
android:roundIcon="#drawable/plant"
android:supportsRtl="true"
android:requestLegacyExternalStorage="true"
android:theme="#style/AppTheme">
<activity android:name=".Donenewplant"></activity>
<activity android:name=".newPlant" />
<activity android:name=".MainActivity" />
<activity android:name=".Splash_screen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.varroxsystems.plant.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths" />
</provider>
</application>
</manifest>
So does anyone know a solution for that, or is it just a bug, because I use the same exact code in another app and it works just fine.
EDIT: The other app I use uses a different database, not the same one.

Passing parameters in firebase dynamic link not working

I am new to firebase. I was using an old version code where the parameters i put were atleast working for the url. but now when link is clicked, the browser opens and its a 400 error that requested url was not found. it works with only the dynamic link
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Uri BASE_URI = Uri.parse("http://example.com/");
Uri APP_URI = BASE_URI.buildUpon().
appendQueryParameter("extra1", "value").build();
String encodedUri = null;
try {
encodedUri = URLEncoder.encode(APP_URI.toString(), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Log.v("ENCODED URI: ", encodedUri);
Uri deepLink = Uri.parse("https://eh62u.app.goo.gl/y6N7/?link="+encodedUri);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_EMAIL, "");
intent.putExtra(Intent.EXTRA_SUBJECT, "GET TICKETS" );
intent.putExtra(Intent.EXTRA_TEXT, "Click here to get the booked tickets: " + deepLink);
startActivity(Intent.createChooser(intent, "Send Email"));
}
});
}
Main Activity OnCreate code:
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
FirebaseDynamicLinks.getInstance().getDynamicLink(getIntent())
.addOnSuccessListener(this, new OnSuccessListener<PendingDynamicLinkData>() {
#Override
public void onSuccess(PendingDynamicLinkData data) {
if (data == null) {
Log.d("NULL DATA ", "getInvitation: no data");
return;
}
// Get the deep link
Uri deepLink = data.getLink();
String requestId2 = deepLink.getQueryParameter("extra1");
// Handle the deep link
// [START_EXCLUDE]
Log.d("DEEP LINK URL ", "deepLink:" + deepLink);
if (deepLink != null) {
if(requestId2 == "value") {
Intent intent = new Intent(getApplicationContext(), Main2Activity.class);
startActivity(intent);
}
}
// [END_EXCLUDE]
}
})
.addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w("onFailure: ", "getDynamicLink:onFailure", e);
}
});
Android Manifest Code:
<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>
<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:host="example.com"
android:scheme="https"/>
</intent-filter>
</activity>
<activity android:name=".Main2Activity">
</activity>
</application>
how do i put the parameter and then get it in the onSuccess? Thanks
The problem that i finally figured out by trial and error was the encoding part of the code. When i removed the :
encodedUri = URLEncoder.encode(APP_URI.toString(), "UTF-8");
part and just passed APP_URI to the deep link like
Uri deepLink = Uri.parse("https://eh62u.app.goo.gl/y6N7/?link="+APP_URI);
or even constructing the link using builder as:
Uri.Builder URLbuilder = new Uri.Builder()
.scheme("https")
.authority(Constants.DOMAIN)
.path("/")
.appendQueryParameter("link", getBaseUri(value))
.appendQueryParameter("apn", context.getPackageName());
It worked. No Problems. Retrieving the parameter was the usual.

Android Kryonet client wont connect to my PC server?

I made a basic server in eclipse:
Server server;
int tcp = 8885, udp = 8885;
public ServerMain() {
server = new Server();
server.addListener(new Listener() {
public void connected(Connection c) {
System.out.println("Connection made");
}
public void received(Connection c, Object p) {
}
public void disconnected(Connection c) {
System.out.println("Disconnection made");
}
});
server.start();
try {
server.bind(tcp, udp);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new ServerMain();
}
Then I created my client in android studio. I installed the library correctly. (According to google) I put the Kryonet jar into the libs folder and then rebuilt the project. I could then use Kryonet classes. Here is my code for my client:
Client client;
String ip = "MY.IP.ADDRESS";
int tcp = 8885, udp = 8885;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i(TAG, "Start");
client = new Client();
client.addListener(new Listener() {
public void received(Connection c, Object p) {
}
});
client.start();
try {
client.connect(5000, ip, tcp, udp);
Log.i(TAG, "conected");
} catch(IOException e) {
Log.i(TAG, "Error: " + e.getMessage());
}
}
It's the exact same code I would use in a normal Java client except now it's running directly from my android device. I get this error:
Error: Unable to connect to: /MY.IP.ADDRESS:8885
It cannot connect to my IP even though I port forwarded it and all. Why won't it connect? I have read online to add in this to my manifest file:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
So, I did:
<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<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>
</application>
Still to absolutely no avail. What am I doing wrong? (P.S. I have tried with both my network IP, and my public IP. I have no idea what I'm doing wrong, everything works fine with a normal Java program, but with an android app it bugs out.)
Try this code, it's working:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i(TAG, "Start");
client = new Client();
client.addListener(new Listener() {
public void received(Connection c, Object p) {
}
});
client.start();
new ConnectToServer.execute();
}
public class ConnectToServer extends AsyncTask<String, int[], String>
{
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
client.connect(5000, ip, tcp, udp);
Log.i(TAG, "conected");
} catch(IOException e) {
Log.i(TAG, "Error: " + e.getMessage());
return null;
}
}
}

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>

Host is unresolved: api.twitter.com:80

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.

Categories

Resources