I have made a random Image Gallery view with the Android Touch Gallery but I want to Show random Images. I have tried to generate an link with an random number.
I can not Play it and I have no idea how i can solve this.
Please Help.
Activity:
package com.ddd.fun1234;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import ru.truba.touchgallery.GalleryWidget.GalleryViewPager;
import ru.truba.touchgallery.GalleryWidget.UrlPagerAdapter;
import ru.truba.touchgallery.GalleryWidget.BasePagerAdapter.OnItemChangeListener;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
public class GalleryUrlAvtivity extends Activity {
private GalleryViewPager mViewPager;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public Bitmap GetImage() {
Random rn = new Random();
int n = 200000 - 199000 + 1;
int i = rn.nextInt() % n;
URL tempURL = null;
try {
tempURL = new URL("http://miniz.co/RageToonApp/Images/" + rn + ".jpg");
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
List<String> items = new ArrayList<String>();
Collections.addAll(items, tempURL);
UrlPagerAdapter pagerAdapter = new UrlPagerAdapter(this, items);
pagerAdapter.setOnItemChangeListener(new OnItemChangeListener()
{
#Override
public void onItemChange(int currentPosition)
{
}
});
mViewPager = (GalleryViewPager)findViewById(R.id.viewer);
mViewPager.setOffscreenPageLimit(3);
mViewPager.setAdapter(pagerAdapter);
}
}
There is a fail in Collections.addAll. What can I use instead of this?
When you have an idea what i can do or what is a good second Option, please write it.
Daniel
The problem is in these lines:
Random rn = new Random();
...
int i = rn.nextInt() % n;
...
tempURL = new URL("http://miniz.co/RageToonApp/Images/" + rn + ".jpg");
You are calculating i but instead of using it in the URL, you're using rn instead. By default, this calls Random.toString() which contains characters (in this case, a #) that are illegal in URLs.
To fix this you should change the last line to:
tempURL = new URL("http://miniz.co/RageToonApp/Images/" + i + ".jpg");
Related
Dear All I use PagerView to make a slider images and every thing went well
if I use a URL images and String array from drawable images.
But when I use a file stored in my APP directory its not work you will see my code here
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/viewPager"/>
</android.support.constraint.ConstraintLayout>
image_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
app:srcCompat="#mipmap/ic_launcher" />
</LinearLayout>
BitmapPagerAdapter.java
package com.samcotec.pager2;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
public class BitmapPagerAdapter extends PagerAdapter {
Context context;
ArrayList<Bitmap> bitmaps;
LayoutInflater layoutInflater;
public BitmapPagerAdapter(Context context, ArrayList<Bitmap> bitmaps){
this.context = context;
this.bitmaps = bitmaps;
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return bitmaps.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, final int position){
View itemView = layoutInflater.inflate(R.layout.image_layout, container, false);
ImageView imageView = (ImageView) itemView.findViewById(R.id.imageView);
imageView.setImageBitmap(bitmaps.get(position));
container.addView(itemView);
//listening to image click
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "you clicked image " + (position + 1), Toast.LENGTH_LONG).show();
}
});
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout) object);
}
}
MainActivity.java
package com.samcotec.pager2;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
ArrayList<Bitmap> bitmap = new ArrayList<Bitmap>();
ViewPager viewPager;
BitmapPagerAdapter bitmapPagerAdapter;
String imgPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgPath = "/data/data/" + this.getPackageName() + "/" + "quranIMG/";
File savefliepath = new File(imgPath);
if(!savefliepath.exists()){
System.out.println("file not exist: " + imgPath);
savefliepath.mkdir();
}else{
//System.out.println("file exist: " + imgPath);
}
final AssetManager assetManager = getAssets();
String[] list;
InputStream f;
String FileName;
String URLPATH = "http://192.168.100.12/quran/";
Integer StartFrom = 100;
Integer EndTo = 150;
for(int i = StartFrom; i <= EndTo; i++){
FileName = "a-("+i+").png";
File savefile = new File(imgPath + FileName);
if(!savefile.exists()){
// tools.copyAssets(assetManager,Path);
DownloadTask downloadTask = new DownloadTask(URLPATH,imgPath,FileName);
}else{
}
// imgList.add(i);
}
// TODO : we must check internet connection if its ok
for (int i = StartFrom; i<EndTo; i++){
String b = imgPath + "a-("+i+").png";
// System.out.println("file exists" + b);
FileInputStream fiStream;
File imgFile = new File(getFilesDir(), b);
Bitmap bit;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
if(imgFile.exists()){
try{
fiStream = MainActivity.this.openFileInput(b);
bit = BitmapFactory.decodeStream(fiStream);
bitmap.add(bit);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}else{
DownloadTask downloadTask = new DownloadTask(URLPATH,imgPath,"a-("+i+").png");
File imgFile1 = new File(getFilesDir(), b);
if(imgFile1.exists()) {
try{
fiStream = MainActivity.this.openFileInput(b);
bit = BitmapFactory.decodeStream(fiStream);
bitmap.add(bit);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}else{
bit = null;
}
}
}
viewPager = (ViewPager) findViewById(R.id.viewPager);
bitmapPagerAdapter = new BitmapPagerAdapter(MainActivity.this,bitmap);
viewPager.setAdapter(bitmapPagerAdapter);
}
}
I user some tools to download files and store it in imgPath
Images is downloaded and stored and no issue for it
but the issue that
bitmap.size();
always empty and the APP Crashed
The problem is in my DownloadTask not in the code itself.
I solve it by changing the download task to code:
package com.samcotec.pager2;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class DownloadTask {
public DownloadTask(final String url, final String savePath, final String saveName) {
new Thread(new Runnable() {
public void run() {
try {
System.out.println(url+saveName);
URL sourceUrl = new URL(url+saveName);
URLConnection conn = sourceUrl.openConnection();
conn.connect();
InputStream inputStream = conn.getInputStream();
int fileSize = conn.getContentLength();
File savefilepath = new File(savePath);
if (!savefilepath.exists()) {
savefilepath.mkdirs();
}
File savefile = new File(savePath+saveName);
if (savefile.exists()) {
savefile.delete();
}
savefile.createNewFile();
FileOutputStream outputStream = new FileOutputStream(savePath+saveName, true);
byte[] buffer = new byte[1024];
int readCount = 0;
int readNum = 0;
int prevPercent = 0;
while (readCount < fileSize && readNum != -1) {
readNum = inputStream.read(buffer);
if (readNum > -1) {
outputStream.write(buffer, 0, readNum);
readCount = readCount + readNum;
int percent = (int) (readCount * 100 / fileSize);
if (percent > prevPercent) {
System.out.println(percent);
//Toast.makeText(LoadPage.MY_CONTEXT,percent,Toast.LENGTH_LONG);
prevPercent = percent;
}
}
}
outputStream.flush();
outputStream.close();
inputStream.close();
//Thread.sleep(50);
} catch (Exception e) {
System.out.println( e);
}
}
}).start();
}
}
The below code is certainly not the best way of doing what I need to do but unfortunately I don't have much time to go back and change data structures / storage options etc. It will be cleaned up however. Anyway, the quality of the code isn't my problem, I digress.
When the user registers their account for the first time, they are given a ListView with multiple choice (check boxes). The selected items are stored in a SparseBooleanArray then converted to an ArrayList of Strings.
The names of the ListView items are coming from an SQLite database method called getStoreNames() which returns an ArrayList of Strings of the Store names.
I need to then get the Store objects associated with each store name. This is done in the for loop within the continue_button case. (Store store = db.returnStoreByName(storeName)... then adding each of those stores to an ArrayList of Stores.
I am then trying to store this ArrayList of stores in SharedPreferences. Because SPs doesn't support ArrayLists, the data is serialized. In the next Activity when I try to access the Store objects, I deserialize the shared preference object. However when I checked the size of the deserialized ArrayList, it is 0. I checked the arraylist size before I serialized it and put it into shared preferences and it was giving the correct size.
This leads me to believe that somewhere between serializing/deserializing or storing in/retrieving from shared prefs is where something is going wrong and the arraylist is being emptied.
Here is the first activity where the data is saved to shared prefs.
package com.mad.losesano2;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import org.json.JSONArray;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class StoreListRegisterActivity extends AppCompatActivity implements AdapterView.OnItemClickListener, View.OnClickListener{
ListView list_view;
List<String> stores;
DB db;
ArrayList<String> users_stores;
SharedPreferences sp;
Button continue_button;
ArrayList<Store> stores_objects = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_store_list_register);
list_view = (ListView) findViewById(R.id.list_view);
list_view.setOnItemClickListener(this);
list_view.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
list_view.setItemsCanFocus(false);
continue_button = (Button) findViewById(R.id.continue_button);
continue_button.setOnClickListener(this);
db = new DB(getApplicationContext());
stores = db.getStoreNames();
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, stores);
list_view.setAdapter(arrayAdapter);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SparseBooleanArray a = list_view.getCheckedItemPositions();
users_stores = new ArrayList<>();
for (int i = 0; i < stores.size(); i++){
if(a.valueAt(i)){
String store_name = list_view.getAdapter().getItem(a.keyAt(i)).toString();
users_stores.add(store_name);
}
}
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.continue_button:
sp = getSharedPreferences("storeList", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
for (String storeName : users_stores) {
Store store = db.returnStoreByName(storeName);
stores_objects.add(store);
Log.d("LoSeSANO", "Store name: " + store.getName());
try {
editor.putString("usersStores", ObjectSerializer.serialize(stores_objects));
} catch (IOException e) {
e.printStackTrace();
}
}
Log.d("LoSeSANO", "Size: " + stores_objects.size());
Intent intent2 = new Intent(this, LoggedInActivity.class);
startActivity(intent2);
break;
}
}
}
Here is the code where I try to receive the SP object
package com.mad.losesano2;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.io.IOException;
import java.util.ArrayList;
public class LoggedInActivity extends AppCompatActivity {
ArrayList<Store> store_list;
SharedPreferences sp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logged_in);
if (null == store_list) {
store_list = new ArrayList<Store>();
}
sp = getSharedPreferences("storeList", MODE_PRIVATE);
try {
store_list = (ArrayList<Store>) ObjectSerializer.deserialize(sp.getString("usersStores", ObjectSerializer.serialize(new ArrayList<Store>())));
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Log.d("LoSeSANO", "Store name at index 0: " + store_list.get(0).getName()); //store_list size = 0.
}
}
Lastly, here is the ObjectSerializer class
package com.mad.losesano2;
/**
* Created by oshau on 18/03/2018.
*/
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class ObjectSerializer {
public static String serialize(Serializable obj) throws IOException {
if (obj == null) return "";
ByteArrayOutputStream serialObj = new ByteArrayOutputStream();
ObjectOutputStream objStream = new ObjectOutputStream(serialObj);
objStream.writeObject(obj);
objStream.close();
return encodeBytes(serialObj.toByteArray());
}
public static Object deserialize(String str) throws IOException, ClassNotFoundException {
if (str == null || str.length() == 0) return null;
ByteArrayInputStream serialObj = new ByteArrayInputStream(decodeBytes(str));
ObjectInputStream objStream = new ObjectInputStream(serialObj);
return objStream.readObject();
}
public static String encodeBytes(byte[] bytes) {
StringBuffer strBuf = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
strBuf.append((char) (((bytes[i] >> 4) & 0xF) + ((int) 'a')));
strBuf.append((char) (((bytes[i]) & 0xF) + ((int) 'a')));
}
return strBuf.toString();
}
public static byte[] decodeBytes(String str) {
byte[] bytes = new byte[str.length() / 2];
for (int i = 0; i < str.length(); i+=2) {
char c = str.charAt(i);
bytes[i/2] = (byte) ((c - 'a') << 4);
c = str.charAt(i+1);
bytes[i/2] += (c - 'a');
}
return bytes;
}
}
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mad.losesano2/com.mad.losesano2.LoggedInActivity}: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
From this Logcat it's clear that your array size is 0 and you are trying to access index 0. Make sure you check array length before accessing its content.
May be you are getting crash for this line
Log.d("LoSeSANO", "Store name at index 0: " + store_list.get(0).getName());
check store_list size before accessing it's index.
I saw u only store a simple List then you didnt easy way to share data.
Okey with small data like this : SparseBooleanArray a = list_view.getCheckedItemPositions();
I will create class
Class A implement Serializable{
List<String> data;
}
then send Serializable via Intent.
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++;
}
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