In order to show installed applications on the Android emulator, I tried this code. It compiles successfully but doesn't work. What's wrong?
package pack.GetAllInstalledApplications;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.pm.PackageInfo;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class GetAllInstalledApplicationsExample extends Activity {
public ArrayList <PackageInfoStruct> res = new ArrayList <PackageInfoStruct>();
public ListView list;
public String app_labels[];
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getPackages();
list = (ListView)findViewById(R.id.ListView01);
try{
list.setAdapter(new ArrayAdapter<String> (this,android.R.layout.simple_dropdown_item_1line,app_labels));
}catch(Exception e){
System.out.println("Err ++> " + e.getMessage());
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
private ArrayList
<PackageInfoStruct> getPackages() {
ArrayList
<PackageInfoStruct> apps = getInstalledApps(false);
final int max = apps.size();
for (int i=0; i < max; i++) {
apps.get(i);
}
return apps;
}
private ArrayList
<PackageInfoStruct> getInstalledApps(boolean getSysPackages) {
List
<PackageInfo> packs = getPackageManager().getInstalledPackages(0);
try{
app_labels = new String[packs.size()];
}catch(Exception e){
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
for(int i=0;i < packs.size();i++) {
PackageInfo p = packs.get(i);
if ((!getSysPackages) && (p.versionName == null)) {
continue ;
}
PackageInfoStruct newInfo = new PackageInfoStruct();
newInfo.appname = p.applicationInfo.loadLabel(getPackageManager()).toString();
newInfo.pname = p.packageName;
newInfo.versionName = p.versionName;
newInfo.versionCode = p.versionCode;
newInfo.icon = p.applicationInfo.loadIcon(getPackageManager());
res.add(newInfo);
app_labels[i] = newInfo.appname;
}
return res;
}
}
class PackageInfoStruct {
String appname = "";
String pname = "";
String versionName = "";
int versionCode = 0;
Drawable icon;
}
In your call to list.setAdapter you should probably use a different layout. I tried simple_list_item_1
list.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, app_labels));
and it appears to then display the items correctly.
Before rendering the app labels you should add some log in order to understand if you are actually retrieving the apps. Verified that then you can deal with the adapter.
Remember that the ArrayAdapter's constructor get as second parameter the resource id of a text view (otherwise it crashes), so make sure of that.
Moreover, for discarding the system package I use this line of code:
...
if ((pi.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) continue;
...
where pi is the PackageInfo.
Let me know if it works
I change the adapter layout, use the android.R.layout.simple_list_item_1 on your code, and it works.
Related
I'm using this very useful tutorial (https://github.com/RaghavSood/ProAndroidAugmentedReality) for developing a custom AR app.
It works pretty fine, but when I display markers extracted from a file folder (sometimes) the app gets blocked and restarts from the previous activity.
I suppose it's because of the big number of markers situated in the same point of the screen.
Infact, when I lower the radius, and then showing a littler number of markers, the activity continues to work.
Besides, I've tried to modify the function "getTextWidth()" as many people suggest on the net.
I don't know how to reduce the number of Markers drawn on the same point of the screen (so indipendently from reducing the radius). Can you suggest me something? THANKS A LOT!!!!!
I show you the LocalDataSource.java modified:
package com.example.pointofinterests;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import com.example.pointofinterests.R;
import com.example.pointofinterests.IconMarker;
import com.example.pointofinterests.Marker;
/**
* This class should be used as a example local data source. It is an example of
* how to add data programatically. You can add data either programatically,
* SQLite or through any other source.
*
* #author Justin Wetherell <phishman3579#gmail.com>
*/
public class LocalDataSource extends DataSource {
private List<Marker> cachedMarkers = new ArrayList<Marker>();
private static Bitmap icon = null;
public LocalDataSource(Resources res) {
if (res == null) throw new NullPointerException();
createIcon(res);
}
protected void createIcon(Resources res) {
if (res == null) throw new NullPointerException();
icon = BitmapFactory.decodeResource(res, R.drawable.icon);
}
public List<Marker> getMarkers() {
try{
String TestoIDPercorsi = readFileAsString("/sdcard/Epulia/IDPercorsi.txt");
if(TestoIDPercorsi==""){
// DOING NOTHING
}else {
String[] IDPercorso = TestoIDPercorsi.split("#");
for(int l=0; l<IDPercorso.length-1; l++){
String TestoPercorso = readFileAsString("/sdcard/Epulia/Percorso" + IDPercorso[l] + ".txt");
if (TestoPercorso.equals("")){
}else {
ArrayList<String> IDSTEPS2 = new ArrayList<String>();
String[] temp = TestoPercorso.split("#");
for (int j=1; j < temp.length; j++){
Log.d("RIGA_" + j + "_" + IDPercorso[l], temp[j]);
if(temp[j].substring(0,2).contains("P")){//POI
String[] POI = temp[j].split("\\|");
String id = POI[1];
String description = POI[2];
Double lat = Double.parseDouble(POI[3]);
Double lng = Double.parseDouble(POI[4]);
String type = POI[5];
Marker poi = new IconMarker(description, lat,lng, 0, Color.DKGRAY, icon);
cachedMarkers.add(poi);
}
}
}
}
}
}catch (Exception e){
Log.e("EXCEPTION", "> " + e);
}
return cachedMarkers;
}
public static String readFileAsString(String filePath) {
String result = "";
File file = new File(filePath);
if ( file.exists() ) {
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
char current;
while (fis.available() > 0) {
current = (char) fis.read();
result = result + String.valueOf(current);
}
} catch (Exception e) {
Log.d("TourGuide", e.toString());
} finally {
if (fis != null)
try {
fis.close();
} catch (IOException ignored) {
}
}
}
return result;
}
}
I would like to thank the Author of the Tutorial who helped me in fixing the problem.
I report his answer that soled my problem:
Not sure why you have that limitation but this should limit the number of Markers drawn on the screen.
In class AugmentedView.java
You can introduce a new member variable:
private static int MAX_NUM_TO_DRAW = 10;
Then in the method onDraw(Canvas canvas):
You can quit the drawing loop early.
int i=0;
ListIterator<Marker> iter = collection.listIterator(collection.size());
while (iter.hasPrevious() && i<MAX_NUM_TO_DRAW ) {
Marker marker = iter.previous();
marker.draw(canvas);
i++;
}
public void directionSpinner (String directions []) {
//Does some stuff to assign namedDirections [0] and namedDirections[1] a value.
dirSpinner = (Spinner) findViewById(R.id.route_direction_spinner); //THIS IS LINE 87
dirSpinner.setOnItemSelectedListener(this);
ArrayAdapter<CharSequence> adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter.add(namedDirections[0]);
adapter.add(namedDirections[1]);
dirSpinner.setAdapter(adapter);
Log.i(TAG, "spinner populated");
}
LogCat:
12-09 20:50:13.497: E/AndroidRuntime(857): FATAL EXCEPTION: main
12-09 20:50:13.497: E/AndroidRuntime(857): java.lang.NullPointerException
12-09 20:50:13.497: E/AndroidRuntime(857): at android.app.Activity.findViewById(Activity.java:1839)
12-09 20:50:13.497: E/AndroidRuntime(857): at com.nicotera.colton.londontransitguide.RoutesActivity.directionSpinner(RoutesActivity.java:87)
12-09 20:50:13.497: E/AndroidRuntime(857): at com.nicotera.colton.londontransitguide.MyInnerClass.onPostExecute(RoutesActivity.java:142)
12-09 20:50:13.497: E/AndroidRuntime(857): at com.nicotera.colton.londontransitguide.MyInnerClass.onPostExecute(RoutesActivity.java:1)
Anyways, route_direction_spinner is defined correctly. directionSpinner() runs after an AsyncTask is completed.
Entire Code:
package com.nicotera.colton.londontransitguide;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jsoup.*;
import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class RoutesActivity extends Activity implements OnItemSelectedListener {
Spinner dirSpinner;
Spinner routeSpinner;
static String [] namedDirections = new String [2];
private static final String TAG = "RoutesActivity";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_routes);
dirSpinner = (Spinner) findViewById(R.id.route_direction_spinner); // Create an ArrayAdapter using the string array and a default spinner layout
routeSpinner = (Spinner) findViewById(R.id.route_name_spinner); // Create an ArrayAdapter using the string array and a default spinner layout
routeSpinner.setOnItemSelectedListener(this);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.routes_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Apply the adapter to the spinner
routeSpinner.setAdapter(adapter);
Log.i(TAG, "second spinner populated");
}
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
Log.i(TAG, "Item selected");
//DecimalFormat df = new DecimalFormat("00##");
int tempPos = pos;
Log.i(TAG, ("Position of selected item: " + tempPos));
int routeSelected;
if (tempPos < 17)
routeSelected = (tempPos + 1);
else if (tempPos >= 17 && tempPos < 29)
routeSelected = (tempPos + 2);
else
routeSelected = (tempPos + 3);
String temp;
if (routeSelected < 10)
temp = ("0") + routeSelected;
else
temp = ("") + routeSelected;
String url = "http://www.ltconline.ca/WebWatch/MobileAda.aspx?r=" + temp;
new MyInnerClass().execute(url);
}
public void directionSpinner (String directions []) {
int temp;
for (int i = 1; i <=2; i++)
{
temp = Integer.parseInt(directions[i]);
if (temp == 1)
namedDirections[(i-1)] = "Eastbound";
else if (temp == 2)
namedDirections[(i-1)] = "Northbound";
else if (temp == 3)
namedDirections[(i-1)] = "Southbound";
else if (temp == 4)
namedDirections[(i-1)] = "Westbound";
}
//setContentView(R.layout.activity_routes);
dirSpinner.setOnItemSelectedListener(this);
ArrayAdapter<CharSequence> adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter.add(namedDirections[0]);
adapter.add(namedDirections[1]);
dirSpinner.setAdapter(adapter);
Log.i(TAG, "spinner populated");
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
}
class MyInnerClass extends AsyncTask<String, Void, String> {
String [] directions = new String [3];
String [] directionNames = new String [3];
private static final String TAG = "RoutesActivity";
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
RoutesActivity tc = new RoutesActivity();
tc.directionSpinner(directions);
}
#Override
protected String doInBackground(String... params) {
try{
Pattern routeDirPattern = Pattern.compile("\\&d=(\\d{1,2})");
Connection conn = Jsoup.connect(params[0]);
Document doc = conn.get();
int i = 0;
Elements routeLinks = doc.select("a[href]");
for (Element routeLink : routeLinks) {
i = (i + 1);
String name = routeLink.text();
Attributes attrs = routeLink.attributes();
String href = attrs.get("href");
Matcher m = routeDirPattern.matcher(href);
if (m.find()) {
String number = m.group(1);
directions [i] = number;
directionNames [i] = name;
Log.i(TAG, directionNames [i]);
}
}
}catch(Exception e){Log.d("doinbackground exception", e.toString());}
return ("Done");
}
}
Basically, this grabs some values from a transit website. This section of code so far just gets the direction of the route based off the route selected.
(Your directionSpinner() method is different in the two snippets you've posted, and I'm working using the one added later, but this solution should work for both snippets, assuming the problem is the same)
Your problem is that you're not following the Activity lifecycle properly.
When you call:
RoutesActivity tc = new RoutesActivity();
tc.directionSpinner(directions);
You are actually creating a brand new instance of RoutesActivity. And since you're calling it as a standard Java class, it never follows the Activity lifecycle, which means that onCreate() is never called, which in turn means that your two spinner objects remain null (as you assign values to them in onCreate()).
Due to this, when you use:
dirSpinner.setOnItemSelectedListener(this);
dirSpinner is actually null resulting in a NullPointerException.
Instead, try using:
RoutesActivity.this.directionSpinner(directions);
Instead of:
RoutesActivity tc = new RoutesActivity();
tc.directionSpinner(directions);
I am planning to create a world clock widget in android. The clock should show the selected country's time as an analog clock widget. But I'm feeling difficulties as I'm a beginner in android.
My widget.xml file contains the following:-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/Widget"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_margin="8dip"
android:background="#drawable/myshape" >
<AnalogClock android:id="#+id/AnalogClock"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:dial="#drawable/widgetdial"
android:hand_hour="#drawable/widgethour"
android:hand_minute="#drawable/widgetminute"/>
I am using the following configuration activity for my widget:-
(To display the city list)
package nEx.Software.Tutorials.Widgets.AnalogClock;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import android.app.Activity;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.os.Bundle;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AnalogClock;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RemoteViews;
import android.widget.TextView;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ConfigureApp extends Activity {
DateFormat df;
private ListView cityList;
public static String[][] citylist = new String[1242][10];
String[] cities = new String[1242];
String field[] = new String[20];
String list[][] = new String[1242][10];
String country = "";
String line = null;
int row = 0;
int col = 0;
// Variables for list view population
String city = "";
int position = 0;
public int[] listArray = new int[1242];
public static int len = 0;
public String[][] adapterCityList = new String[1242][3];
// Variables for passing intent data
public static final String citieslist = "com.world.citieslist";
AppWidgetManager awm;
Context c;
int awID;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// Set the result to CANCELED. This will cause the widget host to cancel
// out of the widget placement if they press the back button.
setResult(RESULT_CANCELED);
try {
citylist = getCityList();
} catch (IOException e) {
Log.e("Loading CityList", e.getMessage());
}
for (int i = 0; i < 1242; i++) {
cities[i] = citylist[i][0];
}
// Set the view layout resource to use.
setContentView(R.layout.configure);
c = ConfigureApp.this;
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
awID = extras.getInt(
AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
} else{
finish();
}
awm = AppWidgetManager.getInstance(c);
cityList=(ListView)findViewById(R.id.CityList);
// By using setAdpater method in listview we an add string array in list.
cityList.setAdapter(new ArrayAdapter<String> (this,android.R.layout.simple_list_item_1, cities));
// cityList.setOnItemClickListener(cityListListener);
cityList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int pos, long id) {
df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String str = ((TextView) v).getText().toString();
RemoteViews remoteViews = new RemoteViews(c.getPackageName(),
R.layout.widget);
remoteViews.setTextViewText(R.id.mytext, str);
remoteViews.setTextViewText(R.id.date, df.format(new Date()));
Intent in = new Intent(c,clock.class);
PendingIntent pi = PendingIntent.getActivity(c, 0, in, 0);
remoteViews.setOnClickPendingIntent(R.id.Widget, pi);
awm.updateAppWidget(awID, remoteViews);
Intent result = new Intent();
result.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,awID);
setResult(RESULT_OK, result);
finish();
}
});
}
private String[][] getCityList() throws IOException {
Context context = getApplicationContext();
InputStream instream = context.getResources().openRawResource(R.raw.cities_final);
// if file the available for reading
if (instream != null) {
// prepare the file for reading
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
while ((line = buffreader.readLine()) != null) {
field = line.split(",");
for (String x : field) {
list[row][col] = x;
col++;
if (x != null) {
country = x;
}
}
list[row][2] = country;
row++;
col = 0;
}
for (int i = 0; (i < list.length); i++) {
for (int j = 0; (j < 3); j++) {
if (j == 1) {
list[i][j] = list[i][j].substring(0, 6);
}
}
}
}
return list;
}
}
Can I use my own custom view in the widget, apart from analog clock? Or is there any other way to show the clock? like use the Imageview as the clock face and to draw the dial according to the time?
Please help me regarding this.!!!:(
A similar example for thermometer is given in this link
http://mindtherobot.com/blog/272/android-custom-ui-making-a-vintage-thermometer/
You can create your own view and make the clock as well.
You can replaced the clock dial, clock hand minute and clock hand hour with your own drawings. Then You'll have your own custom clock.
android:dial="#drawable/YOUR_OWN_DIAL"
android:hand_hour="#drawable/YOUR_OWN_HOUR"
android:hand_minute="#drawable/YOUR_OWN_MINUTE"
Test the layout in the Graphical Layout Tool to see how it look like.
I am developing an application on Android 2.2 . Mainly what it does , is that it grab data from the internet and then it shows it on the device's screen. I have finished an Activity , but , it is too slow , it takes too much to get the web content . I would like to make it run faster . I guess that Async Task would be the most appropriate method that I should use . I've tried to change the code , to insert the Async Task but I cant figure out how to do it right .
This is my code :
package com.nextlogic.golfnews;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
public class Activity1 extends Activity {
View vw;
ImageView im;
Bitmap bmp;
URL url = null;
//ImageView t;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
String s="";
String pag="";
String aux1="";
ArrayList<String> pg;
ArrayList<String> links;
ArrayList<String> sbt;
TableLayout tableView = (TableLayout) findViewById(R.id.tableView);
String q="";
String tt="";
pag=getPage();
aux1=pag.substring(pag.indexOf("\">Annonse<"),pag.indexOf("<!-- START articleListBullets -->"));
pg=title(aux1);
links=urls(aux1);
sbt=subtitle(aux1);
///////////////////////////////////////////////////////////////////////////
for(int i=0; i<pg.size(); i++) {
s = "http://www.golfnews.no/" +links.get(i);
q=pg.get(i);
tt=sbt.get(i);
// create a new TableRow
TableRow row = new TableRow(this);
row.setBackgroundColor(Color.WHITE);
row.setTag(i);
row.setClickable(true);
row.setClickable(true);
row.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), News.class);
startActivityForResult(myIntent, 0);
}
});
// create a new TextView
TextView fin = new TextView(this);
vw = new View(this);
im = new ImageView(this);
////////////////////////////////////
bmp=getbmp(s);
im.setImageBitmap(bmp);
vw.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, 1));
vw.setBackgroundColor(Color.LTGRAY);
row.addView(im, new TableRow.LayoutParams(70,30));
q=titleEdit(q);
tt=subtitleEdit(tt);
//////////////////////////////////////
fin.setText(Html.fromHtml("<b>" + q + "</b>" + "<br />" +
"<small>" + tt + "</small>"));
row.addView(fin);
tableView.addView(vw);
tableView.addView(row, new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
}
}
public Bitmap getbmp(String s)
{
Bitmap bmp = null;
try{
url = new URL(s);
}
catch(MalformedURLException e)
{
e.printStackTrace();
}
try{
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmp = BitmapFactory.decodeStream(is);
} catch (IOException e)
{
e.printStackTrace();
}
return bmp;
}
public String titleEdit(String q)
{
if(q.length()>33)
{
String q1 = q.substring(0,33);
String q2 = q.substring(33);
q =q1 + "<br />" +q2;
}
return q;
}
public String subtitleEdit(String tt)
{
if(tt.length()>40)
{
String tt1 = tt.substring(0,40);
String tt2 = tt.substring(40);
if(tt2.length()>42)
{
String z1 = tt2.substring(0,40);
String z2 = tt2.substring(40);
if(z2.length()>42)
{
String z21 = z2.substring(0,40);
String z22 = z2.substring(40);
z2=z21+"<br />"+z22;
}
tt2=z1+"<br />"+z2;
}
tt = "<br />"+tt1 + "<br />" +tt2;
}
return tt;
}
private ArrayList<String> title (String trax)
{
ArrayList<String> result= new ArrayList<String>();
int ok=1;
int s1,s2;
while(ok==1)
{
//System.out.println("INDEX = "+trax.indexOf("alt="));
ok=0;
if((trax.indexOf("alt=")!=-1&&trax.indexOf("\"/>")!=-1)&&((trax.indexOf("alt=")<trax.indexOf("\"/>"))))
{
ok=1;
s1 =trax.indexOf("alt=");
s2 = trax.indexOf("\"/>");
//System.out.println("s1= "+s1+" s2 = "+s2+" length="+trax.length());
result.add(trax.substring(s1+5,s2));
// i++;
trax = trax.substring(s2 + 3);
}
}
return result;
}
private ArrayList<String> subtitle (String trax)
{
ArrayList<String> result= new ArrayList<String>();
int ok=1;
int s1,s2;
while(ok==1)
{
ok=0;
if(trax.indexOf("<p>")!=-1)
{
ok=1;
s1 =trax.indexOf("<p>");
s2 = trax.indexOf(")");
//System.out.println("s1= "+s1+" s2 = "+s2+" length="+trax.length());
result.add(trax.substring(s1+3,s2+1));
trax = trax.substring(s2+1 );
}
}
return result;
}
private ArrayList<String> urls (String trax)
{
ArrayList<String> result= new ArrayList<String>();
int ok=1;
int s1,s2;
while(ok==1)
{
//System.out.println("INDEX = "+trax.indexOf("alt="));
ok=0;
if((trax.indexOf("<img src")!=-1&&trax.indexOf("alt=\"")!=-1)&&((trax.indexOf("<img src")<trax.indexOf("alt=\""))))
{
ok=1;
s1 =trax.indexOf("<img src");
s2 = trax.indexOf("alt=\"");
// System.out.println("s1= "+s1+" s2 = "+s2+" length="+trax.length());
result.add(trax.substring(s1+10,s2-2));
// i++;
trax = trax.substring(s2 + 6);
}
}
return result;
}
private String getPage() {
String str = "***";
try
{
HttpClient hc = new DefaultHttpClient();
HttpPost post = new HttpPost("http://golfnews.no/nyheter.php");
HttpResponse rp = hc.execute(post);
if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
str = EntityUtils.toString(rp.getEntity());
}
}catch(IOException e){
e.printStackTrace();
}
return str;
}
}
The Activity takes too much time to load .(About 10 seconds) . So please , can you help me figure out where and how to insert the Async Task ? Or maybe you can suggest me something else to make the application run faster ? Something like a handler for example ? I don't really know much since I am new to Android programming . Any advice would be much appreciated . Thanks.
1) You need improve your code style
2) For such purposes you must use AsynchTask or Handler+Separate Thread
1,2
hello expert, i need build app that share mobile app to second mobile so that
i need know that how can i get all app information like : name,date,icon,etc.
package com.AppInfo;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
public class AppInfo extends Activity {
/** Called when the activity is first created. */
private ListView lView;
private ArrayList results = new ArrayList();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}}
class PInfo {
private String appname = "";
private String pname = "";
private String versionName = "";
private int versionCode = 0;
private Drawable icon;
private void prettyPrint() {
// Log.v(appname + "\t" + pname + "\t" + versionName + "\t" + versionCode);
}
private ArrayList<PInfo> getPackages() {
ArrayList<PInfo> apps = getInstalledApps(false); /* false = no system packages */
final int max = apps.size();
for (int i=0; i<max; i++) {
apps.get(i).prettyPrint();
}
return apps;
}
private ArrayList<PInfo> getInstalledApps(boolean getSysPackages) {
ArrayList<PInfo> res = new ArrayList<PInfo>();
List<PackageInfo> packs = getPackageManager().getInstalledPackages(0);
for(int i=0;i<packs.size();i++) {
PackageInfo p = packs.get(i);
if ((!getSysPackages) && (p.versionName == null)) {
continue ;
}
PInfo newInfo = new PInfo();
newInfo.appname = p.applicationInfo.loadLabel(getPackageManager()).toString();
newInfo.pname = p.packageName;
newInfo.versionName = p.versionName;
newInfo.versionCode = p.versionCode;
newInfo.icon = p.applicationInfo.loadIcon(getPackageManager());
res.add(newInfo);
}
return res;
}
checkout this : http://www.androidsnippets.com/get-installed-applications-with-name-package-name-version-and-icon
Although the info you want can be retrieved using getInstalledPackages() and using PackageInfo
But as you want to share the app from one phone to another I dont think its possible atleast unless the device is rooted
C2MD is nice to send small amount of data and its fairly easy to implement. If you dont want to do that just send a sms to the other phone and have a receiver on the second mobile.
You can retrieve the information you need using the PackageManager, both ApplicationInfo and PackageInfo may be used.
private static final String TAG = "MyActivity";
...
final PackageManager pm = getPackageManager();
final List<ApplicationInfo> installedApps = pm.getInstalledApplications(PackageManager.GET_META_DATA);
for ( ApplicationInfo app : installedApps ) {
Log.d(TAG, "Package: " + app.packageName);
Log.d(TAG, "Directory: " + app.sourceDir);
Log.d(TAG, "Icon: " + app.icon);
try {
PackageInfo packageInfo = pm.getPackageInfo(app.packageName, PackageManager.GET_PERMISSIONS);
Date installTime = new Date( packageInfo.firstInstallTime );
Date updateTime = new Date( packageInfo.lastUpdateTime );
Log.d(TAG, "Installed: " + installTime.toString());
Log.d(TAG, "Updated: " + updateTime.toString());
Log.d(TAG, "Version: " + packageInfo.versionCode);
Log.d(TAG, "Name: " + packageInfo.versionName);
}
catch ( PackageManager.NameNotFoundException e ) {
e.printStackTrace();
}
}