Get variable other class java Android - java

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.
}
}

Related

Android studio networking fails

I am trying to write an app for android but am not able to connect to the website. the website is
here. I am able to connect to the website in Firefox and chrome. I wrote a simple program in java SE and it is able to connect to the website. here is the code.
import java.net.*;
import java.io.*;
public class urltest {
public static void main( String[] args ) throws Exception {
URL url = new URL ( "https://alerts.weather.gov/cap/mn.php?x=0" );
BufferedReader reader = new BufferedReader( new InputStreamReader( url.openStream() ) );
String line;
while ( ( line = reader.readLine() ) != null )
System.out.println( line );
reader.close();
}
}
This program does work and does connect to the website. the android app however does not. here is the manifest file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ledorianindustries.rss2">
<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/Theme.Rss2">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
and here is the MainActivity.
package com.ledorianindustries.rss2;
import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new rss().execute();
}
public class rss extends AsyncTask<Integer, Void, Exception> {
#Override
protected Exception doInBackground(Integer... integers) {
try {
URL url = new URL("https://alerts.weather.gov/cap/mn.php?x=0");
BufferedReader reader = new BufferedReader( new InputStreamReader( url.openStream() ) );
String line;
while ((line = reader.readLine()) != null) {
Log.e("info", line);
}
reader.close();
} catch (IOException e) {
Log.e("info", e.toString());
}
return null;
}
}
}
for reasons that I cannot identify I am presented with the error:
2021-02-16 12:19:59.363 13978-14006/com.ledorianindustries.rss2 E/info: java.io.FileNotFoundException: https://alerts.weather.gov/cap/mn.php?x=0
I have checked to see if google is using their own implementation of the networking stack and as far as I can tell they have not. So then why does it work in java SE but not in android? I would appreciate some help on this matter.
***edit 1
the code for URLConnection will follow.
URL url = new URL("https://alerts.weather.gov/cap/mn.php?x=0");
//BufferedReader reader = new BufferedReader( new InputStreamReader( url.openStream() ) );
URLConnection uc = url.openConnection();
BufferedReader reader = new BufferedReader( new InputStreamReader( uc.getInputStream() ) );
String line;
while ((line = reader.readLine()) != null) {
Log.e("info", line);
}
reader.close();
the error code is:
2021-02-16 14:12:28.132 14638-14698/com.ledorianindustries.rss2 E/info: java.io.FileNotFoundException: https://alerts.weather.gov/cap/mn.php?x=0
***edit2
I have tried a few other urls:
URL url1 = new URL("https://alerts.weather.gov/cap/mn.php?x=0");
URL url2 = new URL("https://www.rediff.com/rss/moviesreviewsrss.xml");
URL url3 = new URL("https://www.cinemablend.com/rss_review.php");
url1 is the original url. url2 and url3 work. I am starting to think the "?x=0" may be the problem? I don't know much about php but is that maybe the issue? can php be rewritten? I tried to remove that part in my browser, it was very unhappy.

"App" has unfortunately stopped working caused by "could not find method android.view.Window$Callback" errors

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

HTTP Basic Authorization Network Issue on Android

I'm having a problem querying a database in Ragic off of Android. I've SUCCESSFULLY created a program in Eclipse that queries the online database and downloads all the JSONS, turns them into Objects, and then puts them into an ArrayList. Unfortunately, I'm running into a problem trying to download the same data using the exactly same code in Android. I've already added the permission for the internet (as shown in the AndroidManifest.xml). The code compiles and all, but throws the NullPointerException("RUNTIME EXCEPTION/ALLDOWNLOADEXCEPTIONS") at the end of the MapsActivity.java file. That is the problem, but I don't know what it causing it. Please help with that.
Here is the MapsActivity.java:
package com.main.parcaretestversion;
import android.graphics.Color;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import java.io.*;
import java.net.*;
import java.util.*;
import com.google.android.gms.maps.model.Polygon;
import com.google.android.gms.maps.model.PolygonOptions;
import com.google.gson.*;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
ArrayList<ParkingSpot> list = init();
System.exit(0);
for (ParkingSpot spot: list) {
PolygonOptions rectOptions = new PolygonOptions()
.addAll(spot.getArrayListLatLngDefault());
if (spot.getStatus()) {
rectOptions.fillColor(Color.GREEN);
} else {
rectOptions.fillColor(Color.RED);
}
Polygon polygon = mMap.addPolygon(rectOptions);
}
}
public ArrayList<ParkingSpot> format(String input) {
ArrayList<ParkingSpot> list = new ArrayList<ParkingSpot>();
JsonElement root = new JsonParser().parse(input);
for (int i = 0; i <= 9; i++) {
String uid = root.getAsJsonObject().get(String.valueOf(i) + "").getAsJsonObject().get("ID").getAsString();
String coordinate1 = root.getAsJsonObject().get(String.valueOf(i) + "").getAsJsonObject().get("Coordinate 1").getAsString();
String coordinate2 = root.getAsJsonObject().get(String.valueOf(i) + "").getAsJsonObject().get("Coordinate 2").getAsString();
String coordinate3 = root.getAsJsonObject().get(String.valueOf(i) + "").getAsJsonObject().get("Coordinate 3").getAsString();
String coordinate4 = root.getAsJsonObject().get(String.valueOf(i) + "").getAsJsonObject().get("Coordinate 4").getAsString();
String statusTemp = root.getAsJsonObject().get(String.valueOf(i) + "").getAsJsonObject().get("Status").getAsString();
boolean status;
if (statusTemp.equals("true")) {
status = true;
} else {
status = false;
}
list.add(new ParkingSpot(uid, status, new LatLong(coordinate1), new LatLong(coordinate2), new LatLong(coordinate3), new LatLong(coordinate4)));
}
return list;
}
public ArrayList<ParkingSpot> init() {
String apiKey = "some api key";
try {
//
URL url = new URL("https://api.ragic.com/some username/some sheet/1");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setRequestProperty("Authorization", "Basic " + apiKey);
InputStream content = (InputStream) connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String uglyJson = "";
for (String line; (line = reader.readLine()) != null; ) {
uglyJson += line;
}
ArrayList<ParkingSpot> list = format(uglyJson);
throw new NullPointerException(uglyJson);
//return list;
} catch (MalformedURLException e) {
throw new NullPointerException("MALFORUMED URL EXCEPTION");
} catch (RuntimeException allDownloadExceptions) {
throw new NullPointerException("RUNTIME EXCEPTION/ALLDOWNLOADEXCEPTIONS");
} catch (ProtocolException e) {
throw new NullPointerException("PROTOCOL EXCEPTION");
} catch (IOException e) {
throw new NullPointerException("IO EXCEPTION");
}
}
}
Here is the AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Use asyncTasks in your mainActivity.
For example.
private class LongOperation extends AsyncTask<String, Void, ArrayList> {
#Override
protected ArrayList doInBackground(String... params) {
URL url = new URL("https://api.ragic.com/some username/some sheet/1");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setRequestProperty("Authorization", "Basic " + apiKey);
InputStream content = (InputStream) connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String uglyJson = "";
for (String line; (line = reader.readLine()) != null; ) {
uglyJson += line;
}
ArrayList<ParkingSpot> list = format(uglyJson);
throw new NullPointerException(uglyJson);
return list;
}
#Override
protected void onPostExecute(ArrayList result) {
//Handle result here.
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
now make call for this call
new LongOperation().execute();
Hope it will help

How to display parsed html in a ListView in Android

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.

Why read logcat in loop read only one time

I run my service (write logcat to file) on any emulators and real devices from 2.3.3 to 4.1. All OK.
On this devices generated right log:
--------- beginning of /dev/log/main
--------- beginning of /dev/log/system
I/ActivityManager( 3386): START {act=android.intent.action.MAIN cat=[android.intent.category.HOME] flg=0x10000000 cmp=com.android.launcher/com.androWAcivtMaae( 36:IvldakgNme W/ActivityManager( 3386): Duplcaefns eus orcitRod45c6 o.vnotsolet.tiiyilg
I/ActivityManager( 3386): Displayed com.android.calculator2/.Calculator: +9s374ms<br>
.....
.....
But when I run service on 4.1.2 (samsung (google) Nexus S (soju, crespo), SDK 16, flash 485486, build JZO54K) or 2.3.6, my service stoped after one line in logs.
On this devices generated wrong log:
--------- beginning of /dev/log/main
Only print one line and nothing.... Service stay in memory, but not work right...
This is my code
AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.my.logcatt"
android:versionCode="1"
android:versionName="0.5">
<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.READ_LOGS" />
<application android:theme="#android:style/Theme.NoTitleBar">
<activity android:name=".ActivityMain" android:label="logcatt">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".BroadcastBoot" android:enabled="true" android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:name=".ServiceMain" android:enabled="true" />
</application>
</manifest>
Activity
package com.my.logcatt;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class ActivityMain extends Activity
{
#Override
public void onCreate( Bundle savedInstanceState)
{
super.onCreate( savedInstanceState);
setContentView( R.layout.main);
try { startService( new Intent( getApplicationContext(), ServiceMain.class)); } catch( Exception e) {}
}
}
Service
package com.my.logcatt;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.InputStreamReader;
import android.app.Service;
import android.content.Intent;
import android.os.Environment;
import android.os.IBinder;
public class ServiceMain extends Service
{
public static Process procLogcatClean = null;
public static Process procLogcatAM = null;
public static BufferedReader readerLogcat = null;
public static void fLog( String sLogMessage)
{
FileWriter fileLog = null;
BufferedWriter bufferLog = null;
try
{
fileLog = new FileWriter( Environment.getExternalStorageDirectory().getAbsolutePath() + "/123.log", true);
if( fileLog != null)
{
bufferLog = new BufferedWriter( fileLog);
bufferLog.write( sLogMessage + "\r\n");
bufferLog.flush();
}
}
catch( Exception e) {}
finally
{
if( bufferLog != null) { try { bufferLog.close(); } catch( Exception e) {} }
if( fileLog != null) { try { fileLog.close(); } catch( Exception e) {} }
}
}
#Override
public void onCreate()
{
super.onCreate();
startService();
}
#Override
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public void onDestroy()
{
super.onDestroy();
}
public void startService()
{
final Thread thread = new Thread()
{
public void run()
{
try
{
Runtime localRuntimeClear = Runtime.getRuntime();
String[] sLogcatClear = new String[ 2];
sLogcatClear[ 0] = "logcat";
sLogcatClear[ 1] = "-c";
procLogcatClean = localRuntimeClear.exec( sLogcatClear);
procLogcatClean.waitFor();
Runtime localRuntimeAM = Runtime.getRuntime();
String[] sLogcatAM = new String[ 2];
sLogcatAM[ 0] = "logcat";
sLogcatAM[ 1] = "ActivityManager:I *:S";
procLogcatAM = localRuntimeAM.exec( sLogcatAM);
readerLogcat = new BufferedReader( new InputStreamReader( procLogcatAM.getInputStream()), 1024);
String str = "";
while( true)
{
str = "";
try
{
if( readerLogcat != null)
{
str = readerLogcat.readLine();
fLog( str);
}
}
catch( Exception e) {}
if( str.compareTo( "") == 0) continue;
}
}
catch( Exception e) {}
finally {}
}
};
thread.setPriority( Thread.MAX_PRIORITY);
thread.start();
}
}
What is wrong?
On 4.1.2., Only rooted and system applications can access logcat. If rooted, you could use "su logcat".
https://groups.google.com/forum/?fromgroups=#!topic/android-developers/6U4A5irWang
I suspect that you will find that this line throws an exception which you do not handle (bad practice btw - if you had a proper catch, you would have found this I think).
procLogcatAM = localRuntimeAM.exec( sLogcatAM);
Otherwise, check for the Android version and do something different or check for the permission refusal. Or, restrict your app to < 4.1.

Categories