I'm trying to parse news titles from a website using jsoup and display them in a ListView. I have been trying to solve this problem for a long time and have googled like crazy but i am unable to solve my problem or find a working solution. I have a custom class that holds two variables the news title and the link to the article. It seems as if everything parses fine but I just can't get my ListView to display correctly or at all... it continually crashes and it seams that every time I get a different error. Maybe I am making it too hard on myself. I am frustrated and can't think logically anymore... I would really appreciate any and all tips or helpful answers.
Feeds class:
public class Feeds {
private String mNewsTitle;
private String mNewsLink;
public Feeds(String newsTitle, String newsLink){
mNewsTitle = newsTitle;
mNewsLink = newsLink;
}
public String getNewsTitle(){
return mNewsTitle;
}
public void setNewsTitle(String newsTitle){
mNewsTitle = newsTitle;
}
public String getNewsLink(){
return mNewsLink;
}
public void setNewsLink(String newsLink){
mNewsTitle = newsLink;
}
}
NewsFeeds class:
public class NewsFeeds extends ListActivity {
private ArrayList<Feeds> mFeedDB = new ArrayList<Feeds>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news_feeds);
HtmlParser htmlThread = new HtmlParser();
htmlThread.execute();
} // end on create
public class HtmlParser extends AsyncTask<Void, Integer, ArrayList<Feeds>> {
private static final int NETWORK_NO_ERROR = -1;
private static final int NETWORK_HOST_UNREACHABLE = 1;
private static final int NETWORK_NO_ACCESS_TO_INTERNET = 2;
private static final int NETWORK_TIME_OUT = 3;
Integer serverError = NETWORK_NO_ERROR;
ProgressDialog dialog;
protected void onPreExecute() {
// example of setting up something
dialog = new ProgressDialog(NewsFeeds.this);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setMessage("Retrieving News Feeds");
dialog.show();
} // end onPreExecute
#Override
protected ArrayList<Feeds> doInBackground(Void... params) {
try {
// need http protocol
Document doc = Jsoup.connect("http://baseball-potsdam.de/news")
.get();
// get news feed titles
Elements newsFeed = doc.getElementsByClass("gdlr-blog-title");
// get all links
Elements links = newsFeed.select("a[href]");
for (Element link : links) {
// populate ArrayList with news titles and links
mFeedDB.add(new Feeds(link.text(), link.attr("href")));
}
return mFeedDB;
// } catch (IOException e) {
// e.printStackTrace();
} catch (ConnectException e) {
serverError = NETWORK_NO_ACCESS_TO_INTERNET;
return null;
} catch (UnknownHostException e) {
serverError = NETWORK_HOST_UNREACHABLE;
return null;
} catch (SocketTimeoutException e) {
serverError = NETWORK_TIME_OUT;
return null;
} catch (IOException e) {
e.printStackTrace();
} // end try catch
return null;
} // end doInBackground
protected void onProgressUpdate(Integer... progress) {
} // end onProgressUpdate
protected void onPostExecute(ArrayList<Feeds> result) {
if (result != null) {
ListView listview = (ListView) findViewById(R.id.list_view_news_feeds);
listview.setAdapter(new ArrayAdapter<Feeds>(NewsFeeds.this, android.R.layout.simple_list_item_1 , mFeedDB));
if (dialog.isShowing()) {
dialog.dismiss();
} // end if
} else {
switch (serverError) {
case NETWORK_NO_ERROR:
Toast.makeText(NewsFeeds.this,
"Probably, invalid response from server",
Toast.LENGTH_LONG).show();
break;
case NETWORK_NO_ACCESS_TO_INTERNET:
// You can customize error message (or behavior) for
// different type of error
case NETWORK_TIME_OUT:
case NETWORK_HOST_UNREACHABLE:
Toast.makeText(NewsFeeds.this, "Error in Connection",
Toast.LENGTH_LONG).show();
break;
}
} // end if else
} // end onPostExecute
} // end HtmlParser class
} // end NewsFeeds
activity_news_feeds.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/list_view_news_feeds"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:dividerHeight="0.1dp"
android:divider="#0000CC"
/>
</LinearLayout>
NewsManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.kylehopeman.android.porcupinesnews"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET" />"
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.kylehopeman.android.porcupinesnews.MainMenu"
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.kylehopeman.android.porcupinesnews.NewsFeeds"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.kylehopeman.android.porcupinesnews.NewsFeeds" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
If you are getting an error with the ListView it looks like it only gets instantiated in the postExecute block. Is it possible to instantiate it in the onCreate() and have it declared where you declare mFeedDB?
After changing the first line in my NewsFeeds.java file from:
public class NewsFeeds extends ListActivity
to:
public class NewsFeeds extends Activity
the errors went away, the app compiled and worked just like I wanted it to.
Related
I am building a mobile app for my project on which I have to retrieve data sent to Thingspeak on it.
When I tap on an image button, it should open a new activity which will show its last value retrieved from Thingspeak.
The issue I am getting is that the app stops working when I click on an image button which is supposed to bring me to another activity. It does open a new activity showing that navigation to another activity is working but then it shows "Smart Agriculture has unfortunately stopped working". I think the problem is in the xml files of the activities or the TextView I have used in some TempHumidity.java file but I don't really know how to resolve them being an absolute beginner in Android Studio. I have 5 files namely activity_main.xml, MainActivity.java, TempHumidity.java, AndroidManifest.xml, imgbtnmenu.xml
TempHumidity.java class(it contains the HttpURLConnection codes)
public class TempHumidity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.imgbtnmenu);
new GetMethodDemo().execute("https://thingspeak.com/channels/357670/field/1/last");
}
public class GetMethodDemo extends AsyncTask<String , Void ,String> {
String server_response;
private TextView aTextView;
#Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
server_response = readStream(urlConnection.getInputStream());
Log.v("CatalogClient", server_response);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.e("Response", "" + server_response);
aTextView.setText(s);
}
}
// Converting InputStream to String
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.teerna.smartagriculture">
<uses-permission android:name="android.permission.INTERNET" />
<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"
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=".TempHumidity"> // you need to add these 3 lines inside application tag.
</activity>
</application>
</manifest>
imgbtnmenu.xml for the new activity menu(the menu that opens when Humidity and Temperature image button is tapped)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
The messages on Logcat are as follows:
Most of the logcat is only warning, you can see the W/ character. The The app crashes because you're receiving a java.lang.VerifyError which is Could not find class 'android.graphics.drawable.RippleDrawable. This error will only happen on pre-lolipop device (Android 5.0)
Try add these line to build.gradle:
android {
defaultConfig {
vectorDrawables.useSupportLibrary = true
}
}
If it still not working, change app:srcCompat inside every ImageView to android:src
I'm trying to read USSD response to get Sim balance amount etc, and I'm having issues, I have been reading many questions related to that on Stackoverflow, nothing has worked so far. Except for this that came close: Prevent USSD dialog and read USSD response?. by #HenBoy331
But i'm still having issues with it. My broadcast receiver doesn't get called too. I'm using 4.4.2
But it shows nothing. I can't seem to parse the message and get the balance.
I have a MainActivity to make the phone call, ReceiverActivity to implement broadcast receiver, USSDService class to get the USSD response.
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, USSDService.class));
dailNumber("100");
}
private void dailNumber(String code) {
String ussdCode = "*" + code + Uri.encode("#");
startActivity(new Intent("android.intent.action.CALL", Uri.parse("tel:" + ussdCode)));
}
}
RecieverActivity.java
public class RecieverActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter filter = new IntentFilter("com.times.ussd.action.REFRESH");
this.registerReceiver(new Receiver(), filter);
}
public class Receiver extends BroadcastReceiver {
private String TAG = "XXXX";
#Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("message");
Log.i(TAG, "Got message: " + message);
}
}
}
USSDService.java
public class USSDService extends AccessibilityService {
public String TAG = "XXXX";
#Override
public void onAccessibilityEvent(AccessibilityEvent event) {
Log.d(TAG, "onAccessibilityEvent");
AccessibilityNodeInfo source = event.getSource();
/* if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && !event.getClassName().equals("android.app.AlertDialog")) { // android.app.AlertDialog is the standard but not for all phones */
if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && !String.valueOf(event.getClassName()).contains("AlertDialog")) {
return;
}
if(event.getEventType() == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED && (source == null || !source.getClassName().equals("android.widget.TextView"))) {
return;
}
if(event.getEventType() == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED && TextUtils.isEmpty(source.getText())) {
return;
}
List<CharSequence> eventText;
if(event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
eventText = event.getText();
} else {
eventText = Collections.singletonList(source.getText());
}
String text = processUSSDText(eventText);
if( TextUtils.isEmpty(text) ) return;
// Close dialog
performGlobalAction(GLOBAL_ACTION_BACK); // This works on 4.1+ only
Log.d(TAG, text);
// Handle USSD response here
Intent intent = new Intent("com.times.ussd.action.REFRESH");
intent.putExtra("message", text);
sendBroadcast(intent);
}
private String processUSSDText(List<CharSequence> eventText) {
for (CharSequence s : eventText) {
String text = String.valueOf(s);
// Return text if text is the expected ussd response
if( true ) {
return text;
}
}
return null;
}
#Override
public void onInterrupt() {
}
#Override
protected void onServiceConnected() {
super.onServiceConnected();
Log.d(TAG, "onServiceConnected");
AccessibilityServiceInfo info = new AccessibilityServiceInfo();
info.flags = AccessibilityServiceInfo.DEFAULT;
info.packageNames = new String[]{"com.android.phone"};
info.eventTypes = AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED | AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED;
info.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;
setServiceInfo(info);
}
}
AndroidManifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.dialussd">
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
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>
<service
android:name=".services.USSDService"
android:enabled="true"
android:exported="true"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService" />
</intent-filter>
<meta-data android:name="android.accessibilityservice"
android:resource="#xml/config_service" />
</service>
<receiver android:name=".RecieverActivity$Receiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>
Please, is there any way i'm implementing this wrongly, Or perhaps there is a new way to get USSD responses which works?
After the launch, change the settings manually
Setting->Accessibility Setting -> You can see a option 'your app name'. Turn it on. (This has to be done from as a part of application flow(not manual))
instead of using broadcast receiver use these two lines of code in
add this code in MainActivity
public static void setTextViewToModify(String Text) {
textView.setText(Text);}
and add this in service class with in onAccessibityEvent
MainActivity.setTextViewToModify(text);
I am just in process by learning Android a bit, and i have stumbled on this problem.
I want to do a "custom incoming call screen". My current Solution is a class(IncomingCallInterceptor) that extends from BroadcastReceiver. In IncomingCallInterceptor class i override the onReceive and starting my activity(MainActivity) with layout when the phone is ringing.
In that activity(MainActivity) i have three buttons:
Accept Call, Hang Up, Decline Call
Those buttons should do what they say, Answer the phone, hang up the phone or decline the call.
I have in someway got the Accept Call to work, but not Hang Up and Decline.
Heres my code below:
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.uppgift.six.one.incoming61.sixone" >
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.CALL_PHONE"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<receiver android:name="IncomingCallInterceptor">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE"/>
</intent-filter>
</receiver>
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
</activity>
</application>
</manifest>
IncomingCallInterceptor that extends from BroadcastReceiver:
public class IncomingCallInterceptor extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Context appContext = context.getApplicationContext();
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
String msg = "Phone state changed to " + state;
if (TelephonyManager.EXTRA_STATE_RINGING.equals(state)) {
String incomingNumber = intent.getStringExtra
(TelephonyManager.EXTRA_INCOMING_NUMBER);
msg += ". Incoming number is this " + incomingNumber;
//START MY ACTIVITY!
Intent i = new Intent(appContext, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
appContext.startActivity(i);
}
Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
}
}
Here is my Activity(The Layout is nothing to post, just now is basically three buttons)
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnAnswer = (Button)findViewById(R.id.btnAnswer);
Button btnDecline= (Button)findViewById(R.id.btnDecline);
Button btnHangUp= (Button)findViewById(R.id.btnHangUp);
btnAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_MEDIA_BUTTON);
i.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_UP,
KeyEvent.KEYCODE_HEADSETHOOK));
sendOrderedBroadcast(i, null);
}
});
btnDecline.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Decline Call (I need help here)
}
});
btnHangUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Hang Up Call (I need help here)
}
});
}
In the MainActivity class it is marked by comments where i need some help.
I have also seen something about a "Telephonyservice interface"(thingy) solution, but i don't understand how that worked when i was testing it.
Reject Call:
try {
TelephonyManager tm = (TelephonyManager)
getSystemService(Context.TELEPHONY_SERVICE);
try {
Class c = Class.forName(tm.getClass().getName());
Method m = c.getDeclaredMethod("getITelephony");
m.setAccessible(true);
Object telephonyService = m.invoke(tm); // Get the internal ITelephony object
c = Class.forName(telephonyService.getClass().getName()); // Get its class
m = c.getDeclaredMethod("endCall"); // Get the "endCall()" method
m.setAccessible(true); // Make it accessible
m.invoke(telephonyService); // invoke endCall()
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
}
}
I'm trying to get the RemoteControlClient set up so my app's music can be controlled by the widget that pops up on the lock screen (like SoundCloud, Google Play Music, and other music/video apps work). I'm not sure what's wrong with my code and why it isn't correctly hooking, but here's what I have so far...
A class called MusicService that tries to handle the updates to the RemoteControlClient
public class MusicService extends Service
{
public static final String ACTION_PLAY = "com.stfi.music.action.PLAY";
private RemoteController controller = null;
#Override
public void onCreate()
{
super.onCreate();
System.out.println("Creating the service.");
if(controller == null)
{
controller = new RemoteController();
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
String action = intent.getAction();
System.out.println("Got an action of " + action);
/* Logic to get my Song cur */
controller.register(this);
controller.updateMetaData(cur);
return START_STICKY;
}
#Override
public void onDestroy()
{
super.onDestroy();
System.out.println("Destorying MusicService");
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
This uses a class I have called RemoteController which houses my RemoteControlClient.
public class RemoteController {
private RemoteControlClient remoteControlClient;
private Bitmap dummyAlbumArt;
public void register(Context context)
{
if (remoteControlClient == null)
{
System.out.println("Trying to register it.");
dummyAlbumArt = BitmapFactory.decodeResource(context.getResources(), R.drawable.dummy_album_art);
AudioManager audioManager = (AudioManager) context.getSystemService(context.AUDIO_SERVICE);
ComponentName myEventReceiver = new ComponentName(context.getPackageName(), MediaButtonReceiver.class.getName());
audioManager.registerMediaButtonEventReceiver(myEventReceiver);
// build the PendingIntent for the remote control client
Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
mediaButtonIntent.setComponent(myEventReceiver);
// create and register the remote control client
PendingIntent mediaPendingIntent = PendingIntent.getBroadcast(context, 0, mediaButtonIntent, 0);
remoteControlClient = new RemoteControlClient(mediaPendingIntent);
remoteControlClient.setTransportControlFlags(RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE
| RemoteControlClient.FLAG_KEY_MEDIA_NEXT
| RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS
| RemoteControlClient.FLAG_KEY_MEDIA_PLAY
| RemoteControlClient.FLAG_KEY_MEDIA_PAUSE
);
audioManager.registerRemoteControlClient(remoteControlClient);
}
}
/**
* Update the state of the remote control.
*/
public void updateState(boolean isPlaying)
{
if(remoteControlClient != null)
{
if (isPlaying)
{
remoteControlClient.setPlaybackState(RemoteControlClient.PLAYSTATE_PLAYING);
}
else
{
remoteControlClient.setPlaybackState(RemoteControlClient.PLAYSTATE_PAUSED);
}
}
}
/**
* Updates the state of the remote control to "stopped".
*/
public void stop()
{
if (remoteControlClient != null)
{
remoteControlClient.setPlaybackState(RemoteControlClient.PLAYSTATE_STOPPED);
}
}
public void updateMetaData(Song song)
{
if (remoteControlClient != null && song != null)
{
System.out.println("Updating metadata");
MetadataEditor editor = remoteControlClient.editMetadata(true);
editor.putBitmap(MetadataEditor.BITMAP_KEY_ARTWORK, dummyAlbumArt);
editor.putLong(MediaMetadataRetriever.METADATA_KEY_DURATION, (long)1000);
editor.putString(MediaMetadataRetriever.METADATA_KEY_ARTIST, "Artist");
editor.putString(MediaMetadataRetriever.METADATA_KEY_TITLE, "Title");
editor.apply();
updateState(true);
}
}
/**
* Release the remote control.
*/
public void release() {
remoteControlClient = null;
}
}
Every time I want to update the widget, I call startService(new Intent(MusicService.ACTION_PLAY));. It looks like it correctly creates the service, and it always gets to the point where it says "Updating metadata", but for some reason when I lock my screen and unlock it, I don't see any widget on my lock screen.
Below is the important parts of my manifest as well, seeing as that could somehow cause the issue...
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.stfi"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="17" />
<application
android:hardwareAccelerated="true"
android:allowBackup="true"
android:icon="#drawable/stfi"
android:label="#string/app_name"
android:largeHeap="true"
android:theme="#style/MyActionBarTheme" >
<meta-data
android:name="android.app.default_searchable"
android:value=".activities.SearchActivity" />
<activity
android:name=".StartingToFeelIt"
android:configChanges="orientation|keyboardHidden"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchable" />
</activity>
...other activities listed
<service
android:name=".helpers.MyNotificationService"
android:enabled="true"
android:label="MyNotificationServiceLabel" >
</service>
<service
android:name=".music.MusicService"
android:exported="false" >
<intent-filter>
<action android:name="com.stfi.music.action.PLAY" />
</intent-filter>
<intent-filter>
<action android:name="com.example.android.musicplayer.action.URL" />
<data android:scheme="http" />
</intent-filter>
</service>
<receiver
android:name=".music.MediaButtonReceiver"
android:exported="false" >
</receiver>
</application>
Right now my MediaButtonReceiver doesn't really do much of anything. I'm just trying to get the hooks set up. If you want, this is my MediaButtonReceiver class...
public class MediaButtonReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
System.out.println("Receiving something.");
if (intent.getAction().equals(Intent.ACTION_MEDIA_BUTTON))
{
final KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (event != null && event.getAction() == KeyEvent.ACTION_UP)
{
if (event.getKeyCode() == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE)
{
System.out.println("You clicked pause.");
}
else if(event.getKeyCode() == KeyEvent.KEYCODE_MEDIA_PLAY)
{
System.out.println("You clicked play.");
}
else if (event.getKeyCode() == KeyEvent.KEYCODE_MEDIA_NEXT)
{
System.out.println("You clicked next.");
}
else if (event.getKeyCode() == KeyEvent.KEYCODE_MEDIA_PREVIOUS)
{
System.out.println("You clicked previous.");
}
}
}
}
}
if you can't see remoteControlClient on lock screen you must implement audio focus. You can look here
I'm trying to get textview to display a number, but it will not.
My activity code:
package com.example.gotteron;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Classement extends Activity{
TextView textview;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.classement);
GetCode getCode = new GetCode();
textview = (TextView)findViewById(R.id.textView1);
try {
textview.setText(getCode.test());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Class to get HTMl:
//Package
package com.example.gotteron;
//Import
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class GetCode{
public String test() throws Exception{
//Recupérer le code HTML de la page
URL oracle = new URL("http://www.nationalleague.ch/NL/fr/");
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine;
String s1 = "";
while ((inputLine = in.readLine()) != null)
s1 = s1 + inputLine;
in.close();
int Berne = s1.indexOf(">SC Bern</td>");
String s3 = String.valueOf(Berne);
return s3;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
XML file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#drawable/background">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/firstPosition" />
</LinearLayout>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.gotteron"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.gotteron.Principal"
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="Classement" android:label="#string/app_name"></activity>
<activity android:name="Calendrier" android:label="#string/app_name"></activity>
<activity android:name="Live" android:label="#string/app_name"></activity>
</application>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
EDIT:
Thanks for the code but there's still a problem. When I run the Application the textview displays his default message. During this time, the logcat displays a lot of messages:
http://pastebin.com/244grjYt
and at the end the app crashes
Essentially, this is what the other answers are about. Since you haven't check anything as answer, maybe this will help.
public class MyClass extends Activity {
TextView textview;
public void onCreate(Bundle bundle) {
super.onCreate(savedInstanceState);
setContentView(R.layout.classement);
textview = (TextView)findViewById(R.id.textview);
new NetworkOperation().execute();
}
private class NetworkOperation extends AsyncTask<Void, Void, String> {
protected String doInBackground(Void... params) {
try {
URL oracle = new URL("http://www.nationalleague.ch/NL/fr/");
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine;
String s1 = "";
while ((inputLine = in.readLine()) != null)
s1 = s1 + inputLine;
in.close();
int Berne = s1.indexOf(">SC Bern</td>");
String s3 = String.valueOf(Berne);
return s3;
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
textview.setText(result);
}
}
}
You cannot make a network connection (HTTP connection) i the ui thread, try to move the call to getCode.test() into another thread or better into an AsyncTask..
You are facing NetworkOnMainThread Exception which is quite common on Emulators that are running on API level 11 and more when you are writing Network Related code in UI Thread. You change your code into doInBackground() of an AsyncTask and run it.
In your case as you are throwing Exception in test() it will not crash your app because Exceptions are caught by Exception.
Example Code:
class FetchResultTask extends AsyncTask<Void,Void,String>
{
protected String doInBackground()
{
//your network related code.
}
protected void onPostExecute(String result)
{
super.onPostExecute(result);
//set the result to TextView here.
}
}