import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewParent;
import android.webkit.WebView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewAnimator;
public class NewsScreenAdapter extends BaseAdapter {
LayoutInflater inflater;
public GifDecoderView webview1;
public static viewholder holder;
View view = null;
public static Context context;
public ImageLoader IL;
public String imgUrl;
public static String addurl;
public NewsScreenActivity activity;
String image;
public static String str;
public static Date parsed;
public static String ac, cat_id;
int storyLenght;
public NewsScreenAdapter(NewsScreenActivity a) {
// TODO Auto-generated constructor stub
context = a.getApplicationContext();
this.activity = a;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
IL = new ImageLoader(activity.getApplicationContext());
}
#Override
public int getCount() {
// TODO Auto-generated method stub
// return NewsScreenActivity.arrayList_header.size();
return NewsScreenActivity.TotalDataArray.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public int getItemViewType(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public int getViewTypeCount() {
// TODO Auto-generated method stub
return NewsScreenActivity.TotalDataArray.size();
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi = convertView;
holder = new viewholder();
vi = inflater.inflate(R.layout.newsscren_row, null);
holder.news_header_title = (TextView) vi.findViewById(R.id.header_title);
holder.ll_data = (LinearLayout) vi.findViewById(R.id.data);
vi.setTag(holder);
holder.news_header_title.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
cat_id = NewsScreenActivity.arrayList_header.get(position);
ac = ((NewsScreenActivity.MainData) NewsScreenActivity.TotalDataArray.get(position)).catId;
activity.startActivity(new Intent(activity,CategoryActivity.class).putExtra("id", ac));
}
});
holder.ll_data.removeAllViews();
try {
storyLenght = ((NewsScreenActivity.MainData) NewsScreenActivity.TotalDataArray.get(position)).storyArr.size();
} catch (Exception e) {
// TODO: handle exception
}
Log.d("Adapter ", " story Lenght " + storyLenght);
for (int i = 0; i < storyLenght; i++) {
view = LayoutInflater.from(activity).inflate(R.layout.sub_row, null);
holder.short_text = (TextView) view.findViewById(R.id.short_text);
holder.image = (ImageView) view.findViewById(R.id.image);
holder.des = (TextView) view.findViewById(R.id.des);
holder.date_time = (TextView) view.findViewById(R.id.date_time);
holder.llAdd = (LinearLayout) view.findViewById(R.id.sub_llAdd);
holder.imgAdd = (ImageView) view.findViewById(R.id.imgAdd);
try{
holder.image.setTag(NewsScreenActivity.arrayList_image.get(i));
IL.DisplayImage(
((NewsScreenActivity.ImagesData) ((NewsScreenActivity.StoryData) ((NewsScreenActivity.MainData) NewsScreenActivity.TotalDataArray
.get(position)).storyArr.get(i)).imageArr.get(0)).smallurl, activity, holder.image);
notifyDataSetChanged();
} catch (Exception e) {
// TODO: handle exception
}
try {
holder.short_text.setText(((NewsScreenActivity.StoryData) ((NewsScreenActivity.MainData) NewsScreenActivity.TotalDataArray.get(position)).storyArr.get(i)).title);
holder.des.setText(((NewsScreenActivity.StoryData) ((NewsScreenActivity.MainData) NewsScreenActivity.TotalDataArray.get(position)).storyArr.get(i)).description);
String st = ((NewsScreenActivity.StoryData) ((NewsScreenActivity.MainData) NewsScreenActivity.TotalDataArray
.get(position)).storyArr.get(i)).date;
parsed = new Date(Long.parseLong(st.substring(6, st.length() - 2)));
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy hh:mmaa");
System.out.println(sdf.format(parsed));
String concat = sdf.format(parsed);
String data = concat;
String half1 = data.substring(0, 11);
Log.e("1st date", "" + half1);
SimpleDateFormat display_date = new SimpleDateFormat("dd.MM.yyyy");
Date d_date = new Date();
String dis_date = display_date.format(parsed);
String half2 = data.substring(11, 19);
Log.e("2st time", "" + half2);
SimpleDateFormat currentdate = new SimpleDateFormat("MMM dd,yyyy");
Date currunt = new Date();
String day = currentdate.format(currunt);
if (half1.equalsIgnoreCase(day) == true) {
holder.date_time.setText(half2);
Log.v("if condition", "" + half2);
} else {
half1 = dis_date;
holder.date_time.setText(half1);
Log.v("else condition", "" + half1);
}
Log.e("currunt time", "" + day);
holder.news_header_title.setText(((NewsScreenActivity.MainData) NewsScreenActivity.TotalDataArray
.get(position)).catDisplay);
if (!((NewsScreenActivity.StoryData) ((NewsScreenActivity.MainData) NewsScreenActivity.TotalDataArray
.get(position)).storyArr.get(i)).advertising
.equalsIgnoreCase("null")) {
holder.short_text.setVisibility(view.GONE);
holder.date_time.setVisibility(view.GONE);
holder.des.setVisibility(view.GONE);
imgUrl = ((NewsScreenActivity.StoryData) ((NewsScreenActivity.MainData) NewsScreenActivity.TotalDataArray
.get(position)).storyArr.get(i)).adData.imageurl;
// TODO Auto-generated method stub
addurl = ((NewsScreenActivity.StoryData) ((NewsScreenActivity.MainData) NewsScreenActivity.TotalDataArray
.get(position)).storyArr.get(i)).adData.targeturl;
//-----------------GIF Image view ------------
//holder.imgAdd.setImageBitmap(IL.getBitmap(imgUrl));
holder.imgAdd.setImageBitmap(loadImageFromUrl(imgUrl));
/* InputStream is = null;
try {
is = (InputStream) new URL(imgUrl).getContent();
webview1 = new GifDecoderView(context, is);
activity.setContentView(webview1);
} catch (Exception e) {
return null;
}*/
try {
InputStream is = (InputStream) new URL(imgUrl).getContent();
GifDecoderView webview1 = new GifDecoderView(activity, is);
// GifMovieView webview1 = new GifMovieView(activity, is);
// holder.llAdd.addView(webview1, holder.imgAdd.getLayoutParams());
} catch (Exception e) {
// TODO: handle exception
}
holder.imgAdd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
activity.startActivity(new Intent(activity, AdvertismentActivity.class));
}
});
Log.i("---", "---------" + imgUrl);
holder.llAdd.setVisibility(View.VISIBLE);
}
holder.ll_data.addView(view);
Log.i("Set Tag", position+"OK"+i);
view.setTag(position+"OK"+i);
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String tag = (String) v.getTag();
String[] arr = tag.split("OK");
int p = Integer.parseInt(arr[0]);
int i = Integer.parseInt(arr[1]);
Log.i("Pos and I", p + " " + i );
str = ((NewsScreenActivity.StoryData) ((NewsScreenActivity.MainData) NewsScreenActivity.TotalDataArray .get(p)).storyArr.get(i)).storyid;
Log.i("Pos and I and STR", p + " " + i + " " + str);
Intent intent = new Intent(context,ShowFullDescriprion.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("id", str);
intent.putExtra("cat", p);
intent.putExtra("pos",i);
context.startActivity(intent);
}
});
} catch (Exception e) {
// TODO: handle exception
}
}
return vi;
}
public static String getDate(long milliSeconds, String dateFormat) {
// Create a DateFormatter object for displaying date in specified
// format.
DateFormat formatter = new SimpleDateFormat(dateFormat);
// Create a calendar object that will convert the date and time value in
// milliseconds to date.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milliSeconds);
return formatter.format(calendar.getTime());
}
public static class viewholder {
TextView news_header_title, short_text, des, date_time;
LinearLayout ll_data, llAdd;
public ImageView image, imgAdd;
}
public static Bitmap loadImageFromUrl(String url) {
URL m;
InputStream i = null;
BufferedInputStream bis = null;
ByteArrayOutputStream out =null;
try {
m = new URL(url);
i = (InputStream) m.getContent();
bis = new BufferedInputStream(i,1024 * 8);
out = new ByteArrayOutputStream();
int len=0;
byte[] buffer = new byte[1024];
while((len = bis.read(buffer)) != -1){
out.write(buffer, 0, len);
}
out.close();
bis.close();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
byte[] data = out.toByteArray();
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
//Drawable d = Drawable.createFromStream(i, "src");
return bitmap;
}
}
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.Html;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class ShowFullDescriprion extends Activity implements OnClickListener {
ImageView show_image, adv_image, refresh,show_home;
TextView title_text, des_text, date_time_txt;
Button back_btn;
LinearLayout ll, llAdv;
public static String url, full_des, advertising, adurl = "",img,
targeturl;
ProgressDialog progressDialog;
TextView mDisplay;
AsyncTask<Void, Void, Void> mRegisterTask;
String TAG = "ShowFullDescriprion";
public static ArrayList<String> catId = new ArrayList<String>();
public static ArrayList<String> catDisp = new ArrayList<String>();
public static ArrayList<String> next_arraylist = new ArrayList<String>();
public static ArrayList<String> privious_arraylist = new ArrayList<String>();
//public static ArrayList<String> arrayList_advertising = new ArrayList<String>();
SimpleGestureFilter simpleGestureFilter;
LinearLayout llCat;
TextView tvCatDisp;
private static final int SWIPE_MIN_DISTANCE = 200;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
int swpCnt = 0;
int SWIPE_MAX_VALUE = 1;
int PIC_WIDTH = 0;
private GestureDetector gestureDetector;
View.OnTouchListener gestureListener;
#SuppressWarnings("unused")
private Animation animleftin = null, animleftout = null,
animrightin = null, animrightout = null;
public static String idS, titleS, dateS, descS, next, privious, adv;
public static String bigimageS=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.showfull_description);
back_btn = (Button) findViewById(R.id.button1);
llCat = (LinearLayout) findViewById(R.id.llCategory);
// llCat.setOnClickListener(this);
adv_image = (ImageView) findViewById(R.id.imgAdd);
refresh = (ImageView) findViewById(R.id.refresh_btn);
show_home=(ImageView)findViewById(R.id.showfull_des_home);
llAdv = (LinearLayout) findViewById(R.id.llAdd);
// simpleGestureFilter = new SimpleGestureFilter(this, this);
// int SWIPE_MAX_VALUE_new = ((NewsScreenActivity.MainData) NewsScreenActivity.TotalDataArray.get(getIntent().getExtras().getInt("cat"))).storyArr.size();
//swpCnt = ((CategoryActivity.MainData) CategoryActivity.TotalDataArray.get(getIntent().getExtras().getInt("cat"))).storyArr.indexOf(getIntent().getExtras().getString("id"));
//((NewsScreenActivity.StoryData) ((NewsScreenActivity.MainData) NewsScreenActivity.TotalDataArray .get(p)).storyArr.get(i)).storyid;
//String temp = ((CategoryActivity.StoryData) ((CategoryActivity.MainData) CategoryActivity.TotalDataArray .get(getIntent().getExtras().getInt("cat"))).storyArr.get(getIntent().getExtras().getString("pos"))).storyid;
// Log.i("Show full Description .....", "********************** cat "+getIntent().getExtras().getInt("cat")+" **** id *** "+getIntent().getExtras().getString("id"));
//Log.i("Show full Description .....", "********************** SWIPE_MAX_VALUE_new "+ SWIPE_MAX_VALUE_new+" *** swpCnt **** "+temp +"**** Array *** "+((CategoryActivity.MainData) CategoryActivity.TotalDataArray.get(getIntent().getExtras().getInt("cat"))).storyArr.get(5));
try {
// SWIPE_MAX_VALUE = ((NewsScreenActivity.MainData) NewsScreenActivity.TotalDataArray.get(getIntent().getExtras().getInt("cat"))).storyArr.size();
SWIPE_MAX_VALUE = ((CategoryActivity.MainData) CategoryActivity.TotalDataArray.get(getIntent().getExtras().getInt("cat"))).storyArr.size();
swpCnt = getIntent().getExtras().getInt("pos");
} catch (Exception e) {
// TODO: handle exception
}
url = "http://maritimeglobalnews.com/json/story/"+ getIntent().getExtras().getString("id");
new StoryDataAsyn().execute();
title_text = (TextView) findViewById(R.id.show_full_des_title_txt);
show_image = (ImageView) findViewById(R.id.show_full_des_image);
des_text = (TextView) findViewById(R.id.show_full_des_txt);
date_time_txt = (TextView) findViewById(R.id.show_full_des_datetime_txt);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
show_home.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(getBaseContext(), NewsScreenActivity.class));
finish();
}
});
/* Log.i(TAG,
"================Inside OnCreate Method==============================");
checkNotNull(SERVER_URL, "SERVER_URL");
checkNotNull(SENDER_ID, "SENDER_ID");
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(getBaseContext());
// Make sure the manifest was properly set - comment out this line
// while developing the app, then uncomment it when it's ready.
GCMRegistrar.checkManifest(getBaseContext());
registerReceiver(mHandleMessageReceiver, new IntentFilter(
DISPLAY_MESSAGE_ACTION));
final String regId = GCMRegistrar.getRegistrationId(this);
if (regId.equals("")) {
Log.i(TAG,
"================Inside if in regId=null ==============================");
// Automatically registers application on startup.
GCMRegistrar.register(this, SENDER_ID);
} else {
Log.i(TAG,
"================Inside else in regId=null ==============================");
// Device is already registered on GCM, needs to check if it is
// registered on our server as well.
if (GCMRegistrar.isRegisteredOnServer(this)) {
// Skips registration.
Log.i(TAG,
"================Inside else in regId=null Already register on Server =============================");
mDisplay.append(getString(R.string.already_registered) + "\n");
} else {
Log.i(TAG,
"================Inside else in regId=null trying to register on Server =============================");
// Try to register again, but not in the UI thread.
// It's also necessary to cancel the thread onDestroy(),
// hence the use of AsyncTask instead of a raw thread.
final Context context = this;
mRegisterTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
Log.i(TAG,
"================Inside doInBackground Method==============================");
boolean registered = ServerUtilities.register(context,
regId);
// At this point all attempts to register with the app
// server failed, so we need to unregister the device
// from GCM - the app will try to register again when
// it is restarted. Note that GCM will send an
// unregistered callback upon completion, but
// GCMIntentService.onUnregistered() will ignore it.
if (!registered) {
GCMRegistrar.unregister(context);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
Log.i(TAG,
"================Inside onPostExecute Method==============================");
mRegisterTask = null;
}
};
mRegisterTask.execute(null, null, null);
}
} */
back_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ShowFullDescriprion.this.finish();
}
});
refresh.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new StoryDataAsyn().execute();
}
});
gestureDetector = new GestureDetector(new MyGestureDetector());
gestureListener = new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
};
prepareAnimations();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
return super.onTouchEvent(event);
}
/*boolean net;
//onCreate
net = void isOnline() {
}
if (net == true)
{
//perform internet related tasks in the app
}
//function
public boolean isOnline1() {
ConnectivityManager cm = (ConnectivityManager) this
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo();
return activeNetworkInfo != null;
// return cm.getActiveNetworkInfo().isConnected();
}*/
public class StoryDataAsyn extends AsyncTask<Void, Void, Void> {
// NewsScreenActivity obj = new NewsScreenActivity();
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
// if (isNetworkConnected() == true)
// {
progressDialog = new ProgressDialog(ShowFullDescriprion.this);
progressDialog.setMessage("Loding ...");
progressDialog.setCancelable(false);
progressDialog.show();
/* } else {
AlertDialog connection = new AlertDialog.Builder(
ShowFullDescriprion.this)
.setTitle("No Network Found")
.setMessage(
"Internet Connection Reqired To Use this Application")
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton)
{
}
}).create();
connection.show();
}
*/ }
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
catId.clear();
catDisp.clear();
getData(url);
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (isNetworkConnected() == true) {
progressDialog.dismiss();
title_text.setText(titleS);
/*if(bigimageS!= null && !bigimageS.equals(""))
{
show_image.setImageBitmap(decodeImage(bigimageS));
Log.v("if", ""+bigimageS);
}else
{
show_image.setImageBitmap(decodeImage(null));
Log.v("else", ""+bigimageS);
}
*/
if(isBlank(bigimageS)==true)
{
show_image.setVisibility(View.GONE);
show_image.setImageBitmap(decodeImage(null));
}
else if(isBlank(bigimageS)==false)
{
show_image.setImageBitmap(decodeImage(bigimageS));
}
// show_image.setImageBitmap(loadImageFromUrl(bigimageS));
//show_image.setImageBitmap(decodeImage(bigimageS));
des_text.setText(Html.fromHtml(descS));
Date parsed = new Date(Long.parseLong(dateS.substring(6,
dateS.length() - 2)));
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy hh:mmaa");
System.out.println(sdf.format(parsed));
date_time_txt.setText(sdf.format(parsed));
llCat.removeAllViews();
for (int i = 0; i < catId.size(); i++) {
tvCatDisp = new TextView(ShowFullDescriprion.this);
tvCatDisp.setText("");
tvCatDisp.setText(catDisp.get(i));
tvCatDisp.setBackgroundResource(R.drawable.box);
tvCatDisp.setTextColor(Color.BLACK);
tvCatDisp.setTextSize(18);
tvCatDisp.setTag(i);
Log.e("tvCatDisp............", ""+catDisp.get(i));
tvCatDisp.setOnClickListener(ShowFullDescriprion.this);
tvCatDisp.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int pos = Integer.parseInt(v.getTag().toString());
startActivity(new Intent(ShowFullDescriprion.this,
CategoryActivity.class).putExtra("id",catId.get(pos)));
}
});
llCat.addView(tvCatDisp);
}
llAdv.removeAllViews();
if ((!adurl.equalsIgnoreCase("")) && adurl != null) {
llAdv.setVisibility(View.VISIBLE);
ImageLoader il = new ImageLoader(ShowFullDescriprion.this);
// adv_image.setImageBitmap(il.getBitmap(adurl));
// adv_image.setImageBitmap(loadImageFromUrl(adurl));
try {
InputStream is = (InputStream) new URL(adurl).getContent();
GifDecoderView webview1 = new GifDecoderView(ShowFullDescriprion.this, is);
// activity.setContentView(webview1);
llAdv.addView(webview1,adv_image.getLayoutParams());
// holder.imgAdd.setImageBitmap(IL.getBitmap(imgUrl));
} catch (Exception e) {
}
llAdv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Intent showAdvIntent =new Intent(ShowFullDescriprion.this,AdvertismentActivity.class);
// showAdvIntent.putExtra("id",targeturl);
startActivity(new Intent(getBaseContext(),AdvertismentActivity.class));
Log.e("show add url...", ""+targeturl);
}
});
}
}else
{
llAdv.setVisibility(View.GONE);
AlertDialog connection = new AlertDialog.Builder(
ShowFullDescriprion.this)
.setTitle("No Network Found")
.setMessage(
"Internet Connection Reqired To Use this Application")
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton)
{
// new StoryDataAsyn().execute();
progressDialog.dismiss();
}
}).create();
connection.show();
}
}
}
public boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null) {
return false;
} else
return true;
}
public void getData(String url) {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout
try {
HttpPost request = new HttpPost(url);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse res = httpClient.execute(request);
Log.i("Request", request.toString());
String JsonResponseData = EntityUtils.toString(res.getEntity());
Log.i("JSON", JsonResponseData);
JSONObject mainJsonObj = new JSONObject(JsonResponseData);
titleS = mainJsonObj.getString("Title");
dateS = mainJsonObj.getString("Date");
descS = mainJsonObj.getString("ContentHTML");
next = mainJsonObj.getString("NextStoryEID");
next_arraylist.add(next);
Log.e("next id", "" + next_arraylist);
Log.e("nextstring id", "" + next);
privious = mainJsonObj.getString("PrevStoryEID");
privious_arraylist.add(privious);
Log.e("privious id", "" + privious_arraylist);
Log.e("privious string id", "" + privious);
try {
JSONArray tmpAd = mainJsonObj.optJSONArray("advertising");
adurl = tmpAd.getJSONObject(0).getString("ImageUrl");
targeturl = tmpAd.getJSONObject(0).getString("TargetUrl");
Log.v("target url is", "" + targeturl);
} catch (Exception e) {
// TODO: handle exception
}
try {
JSONArray tmpimg = mainJsonObj.optJSONArray("images");
bigimageS = tmpimg.getJSONObject(0).getString("iPhoneBigImageURL");
Log.v("bigimageS is", "" + bigimageS);
} catch (Exception e) {
// TODO: handle exception
}
JSONArray categJsonArr = mainJsonObj.getJSONArray("categories");
for (int i = 0; i < categJsonArr.length(); i++) {
catId.add(categJsonArr.getJSONObject(i) .getString("CategoryEID"));
catDisp.add(categJsonArr.getJSONObject(i).getString("CategoryDisplay"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static Bitmap loadImageFromUrl(String url) {
URL m;
InputStream i = null;
BufferedInputStream bis = null;
ByteArrayOutputStream out =null;
try {
m = new URL(url);
i = (InputStream) m.getContent();
bis = new BufferedInputStream(i,1024 * 8);
out = new ByteArrayOutputStream();
int len=0;
byte[] buffer = new byte[1024];
while((len = bis.read(buffer)) != -1){
out.write(buffer, 0, len);
}
out.close();
bis.close();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
byte[] data = out.toByteArray();
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
//Drawable d = Drawable.createFromStream(i, "src");
return bitmap;
}
public static Bitmap decodeImage(String arrayList_image) {
URL aURL;
try {
aURL = new URL(arrayList_image);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
return bm;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
public boolean dispatchTouchEvent(MotionEvent me) {
this.gestureDetector.onTouchEvent(me);
return super.dispatchTouchEvent(me);
}
class MyGestureDetector extends SimpleOnGestureListener {
#Override
public boolean onDown(MotionEvent e) {
// TODO Auto-generated method stub
return super.onDown(e);
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
Log.e("Inside onfling", "Call");
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
return false;
// right to left swipe
if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
url = "http://maritimeglobalnews.com/json/story/"+next;
new StoryDataAsyn().execute();
Log.d("url next mate", ""+url);
Log.d("right to left privious.....", ""+next_arraylist);
try {
Log.i("","swip count " + swpCnt+" ***** "+((CategoryActivity.MainData) CategoryActivity.TotalDataArray.get(getIntent().getExtras().getInt("cat"))).storyArr.size());
} catch (Exception e) {
// TODO: handle exception
}
if (swpCnt >= 0 && swpCnt < SWIPE_MAX_VALUE - 1)
{
swpCnt++;
/* url = "http://maritimeglobalnews.com/json/story/"+next;
new StoryDataAsyn().execute();
Log.d("url next mate", ""+url);
Log.d("right to left privious.....", ""+next_arraylist); */
}
}
else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY ){
url = "http://maritimeglobalnews.com/json/story/"+privious;
Log.v("previousid first if", ""+privious);
Log.i("right to left privious first if.....", ""+privious_arraylist);
new StoryDataAsyn().execute();
if (swpCnt > 0 && swpCnt <= SWIPE_MAX_VALUE - 1) {
swpCnt--;
/*url = "http://maritimeglobalnews.com/json/story/"+privious;
Log.v("url",""+url);
Log.v("previousid 2 if", ""+privious);
new StoryDataAsyn().execute(); */
}
try {
Log.i("","swip count " + swpCnt+" ***** "+((CategoryActivity.MainData) CategoryActivity.TotalDataArray.get(getIntent().getExtras().getInt("cat"))).storyArr.size());
} catch (Exception e) {
// TODO: handle exception
}
/*if (swpCnt > 0 && swpCnt <= SWIPE_MAX_VALUE - 1)
{
swpCnt--;
url = "http://maritimeglobalnews.com/json/story/"+privious;
Log.v("previousid 3 if", ""+privious);
Log.i("right to left privious. 3 if", ""+privious_arraylist);
new StoryDataAsyn().execute();
} */
}
return false;
}
}
private void prepareAnimations() {
animleftin = new TranslateAnimation(Animation.RELATIVE_TO_PARENT,
+1.0f, Animation.RELATIVE_TO_PARENT, 0.0f,
Animation.RELATIVE_TO_PARENT, 0.0f,
Animation.RELATIVE_TO_PARENT, 0.0f);
animleftout = new TranslateAnimation(Animation.RELATIVE_TO_PARENT,
0.0f, Animation.RELATIVE_TO_PARENT, -1.0f,
Animation.RELATIVE_TO_PARENT, 0.0f,
Animation.RELATIVE_TO_PARENT, 0.0f);
animrightin = new TranslateAnimation(Animation.RELATIVE_TO_PARENT,
-1.0f, Animation.RELATIVE_TO_PARENT, 0.0f,
Animation.RELATIVE_TO_PARENT, 0.0f,
Animation.RELATIVE_TO_PARENT, 0.0f);
animrightout = new TranslateAnimation(Animation.RELATIVE_TO_PARENT,
0.0f, Animation.RELATIVE_TO_PARENT, +1.0f,
Animation.RELATIVE_TO_PARENT, 0.0f,
Animation.RELATIVE_TO_PARENT, 0.0f);
}
/*#Override
protected void onDestroy() {
Log.i(TAG,
"================Inside OnDestroy Method==============================");
if (mRegisterTask != null) {
mRegisterTask.cancel(true);
}
unregisterReceiver(mHandleMessageReceiver);
GCMRegistrar.onDestroy(this);
super.onDestroy();
}
private void checkNotNull(Object reference, String name) {
Log.i(TAG,
"================Inside checkNotNull Method==============================");
if (reference == null) {
throw new NullPointerException(getString(R.string.error_config,
name));
}
}
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG,
"================Inside OnReceive in BroadcastReceiver Method==============================");
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
mDisplay.append(newMessage + "\n");
}
};*/
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v == tvCatDisp) {
// TODO Auto-generated method stub
startActivity(new Intent(ShowFullDescriprion.this,
CategoryActivity.class).putExtra("id", catId.get((Integer)v.getTag())));
}
}
public static boolean isBlank(String string) {
if (bigimageS == null || bigimageS.length() == 0)
return true;
int l = bigimageS.length();
for (int i = 0; i < l; i++) {
if (!Character.isWhitespace(bigimageS.codePointAt(i)))
return false;
}
return true;
}
}
You're not reusing your list items. This is why the list is starting to "stutter".
There are a lot of answers on this problem that display the concept of reusing ListView items.
Like this one
In general: within your getView method, check if the convertView is null. If it is, inflate your view. If it's not null, just insert the items that you want to display. This should solve your stuttering list view problem.
Please use for existing layout in BaseAdpter as below
ViewHolder holder = null;
if ( convertView == null )
{
/* There is no view at this position, we create a new one.
In this case by inflating an xml layout */
convertView = mInflater.inflate(R.layout.listview_item, null);
holder = new ViewHolder();
holder.toggleOk = (ToggleButton) convertView.findViewById( R.id.togOk );
convertView.setTag (holder);
}
else
{
/* We recycle a View that already exists */
holder = (ViewHolder) convertView.getTag ();
}
this may helps you
Related
I want to record the android click event when I use other apps. For each click, I record its timestamp. So, this app should run background. I use the "getevent" to catch the click event. I am not very familiar with Android operation. My code
has a bug. Its output is not very good, there are many "null"s in the output, and the record is not exactly right.(My app needs root permission)
1.MainActivity.java
package kingofne.seu.edu.ndktest;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private EditText editText = null;
private TextView textView = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
textView = (TextView) findViewById(R.id.textView);
Button btn_start = (Button) findViewById(R.id.btn_start);
if (btn_start != null) {
btn_start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(getApplicationContext(), MyService.class);
int param = 1;
if (editText != null) {
param = Integer.valueOf(String.valueOf(editText.getText()));
}
intent.putExtra("param", param);
startService(intent);
Toast.makeText(getApplicationContext(), "start", Toast.LENGTH_SHORT).show();
textView.setText(String.valueOf(System.currentTimeMillis()));
}
});
}
Button btn_stop = (Button) findViewById(R.id.btn_stop);
if (btn_stop != null) {
btn_stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(getApplicationContext(), MyService.class);
stopService(intent);
Toast.makeText(getApplicationContext(), "stop", Toast.LENGTH_SHORT).show();
}
});
}
}
}
2.MyService.java
package kingofne.seu.edu.ndktest;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MyService extends Service {
private boolean isRunning = false;
private int param = 1;
private Thread captureThread = null;
private volatile boolean doCapture = false;
public MyService() {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (isRunning) {
return START_NOT_STICKY;
}
param = intent.getIntExtra("param", 1);
this.captureThread = new Thread(new Producer());
captureThread.setDaemon(true);
this.doCapture = true;
captureThread.start();
isRunning = true;
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
// stop the thread
this.doCapture = false;
// destroy the thread
this.captureThread = null;
}
private class Producer implements Runnable {
public void run() {
Log.d("ps", "going to run");
Date now = new Date();
SimpleDateFormat sDateFormat = new SimpleDateFormat(
"yyyy-MM-dd-HH-mm-ss");
String str2 = sDateFormat.format(now);
// String location = str2;
//String cmdLine = "getevent -t -l /dev/input/event" + String.valueOf(param) + " > /sdcard/guo" + ".txt";
String cmdLine = "cat /dev/input/event" + String.valueOf(param) + " > /sdcard/guo.txt";
CMDExecute cmd = new CMDExecute();
try {
// cmd.run_su("getevent -t > /sdcard/Yang_"+location+".txt");
cmd.run_su(cmdLine);
} catch (IOException e) {
// TODO Auto-generated catch block
Log.d("ps", "error");
e.printStackTrace();
}
}
};
class CMDExecute {
public synchronized String run(String[] cmd, String workdirectory)
throws IOException {
String result = "";
try {
ProcessBuilder builder = new ProcessBuilder(cmd);
BufferedReader in = null;
// 设置一个路径
if (workdirectory != null) {
builder.directory(new File(workdirectory));
builder.redirectErrorStream(true);
Process process = builder.start();
process.waitFor();
in = new BufferedReader(new InputStreamReader(process
.getInputStream()));
char[] re = new char[1024];
int readNum;
while ((readNum = in.read(re, 0, 1024)) != -1) {
// re[readNum] = '\0';
result = result + new String(re, 0, readNum);
}
}
if (in != null) {
in.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
public synchronized String run_su(String cmd)
throws IOException {
String result = "";
Process p=null;
try {
p = Runtime.getRuntime().exec("su");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DataOutputStream os = new DataOutputStream(p.getOutputStream());
BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream()));
try {
String istmp;
os.writeBytes(cmd+"\n");
//os.writeBytes("exit\n");
os.flush();
os.writeBytes("exit\n");
os.flush();
p.waitFor();
is.close();
os.close();
p.destroy();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} return result;
}
}
}
I am trying to develop a application. It is a radio application. When i use a method to show meta data that time it is creating some problem.
1.Play Pause button are not working smoothly.
2.Taking more time to show layout.
here is the main activity code:
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.TextView;
public class IRadioActivity extends Activity implements
MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener,
MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener {
private String TAG = getClass().getSimpleName();
private MediaPlayer mp = null;
private ImageButton btnPlay;
String title;
String artist;
private static Context con;
Timer timer;
TextView StationName;
String Stationurl = "http://95.211.82.139:8048";
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
IRadioActivity.con = this;
btnPlay = (ImageButton) findViewById(R.id.btnPlay);
mp = new MediaPlayer();
mp.setOnCompletionListener(this); // Important
btnPlay.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// check for already playing
if (mp.isPlaying()) {
if (mp != null) {
mp.pause();
// Changing button image to play button
btnPlay.setImageResource(R.drawable.btn_play);
}
} else {
// Resume song
if (mp != null) {
mp.start();
// Changing button image to pause button
btnPlay.setImageResource(R.drawable.btn_pause);
}
}
}
});
playSong();
getMeta();
}
public void playSong() {
// Play song
try {
mp.reset();
mp.setDataSource(Stationurl);
mp.prepare();
mp.start();
// Displaying Song title
// Changing Button Image to pause image
btnPlay.setImageResource(R.drawable.btn_pause);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void onDestroy() {
super.onDestroy();
mp.release();
}
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
}
// ----------------
public boolean onError(MediaPlayer mp, int what, int extra) {
StringBuilder sb = new StringBuilder();
sb.append("Media Player Error: ");
switch (what) {
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
sb.append("Not Valid for Progressive Playback");
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
sb.append("Server Died");
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
sb.append("Unknown");
break;
default:
sb.append(" Non standard (");
sb.append(what);
sb.append(")");
}
sb.append(" (" + what + ") ");
sb.append(extra);
Log.e(TAG, sb.toString());
return true;
}
public void onBufferingUpdate(MediaPlayer mp, int percent) {
Log.d(TAG, "PlayerService onBufferingUpdate : " + percent + "%");
}
// .....top bar button....//
public void getMeta() {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
URL url;
// Message msg = handler.obtainMessage();
try {
// url = new URL("http://relay5.slayradio.org:8000");
url = new URL(Stationurl);
final IcyStreamMeta icy = new IcyStreamMeta(url);
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
// Typeface book = Typeface.createFromAsset(
// getAssets(), "fonts/Neutra2Text-Book.otf");
final TextView songTitle = (TextView) findViewById(R.id.songName);
final TextView artistName = (TextView) findViewById(R.id.artistName);
try {
artistName.setText(icy.getArtist().toString()
.trim());
artistName.setText(icy.getArtist().toString()
.trim());
songTitle.setText(icy.getTitle().toString()
.trim());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, 0, 500);
}
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
}
}
Facing those problems when i use getMeta(); method.
Main Class for this method is:
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class IcyStreamMeta<Message> {
protected URL streamUrl;
private Map<String, String> metadata;
private boolean isError;
public IcyStreamMeta(URL streamUrl) {
setStreamUrl(streamUrl);
isError = false;
}
/**
* Get artist using stream's title
*
* #return String
* #throws IOException
*/
public String getArtist() throws IOException {
Map<String, String> data = getMetadata();
if (!data.containsKey("StreamTitle"))
return "";
String streamTitle = data.get("StreamTitle");
String title = streamTitle.substring(0, streamTitle.indexOf("-"));
return title.trim();
}
/**
* Get title using stream's title
*
* #return String
* #throws IOException
*/
public String getTitle() throws IOException {
Map<String, String> data = getMetadata();
if (!data.containsKey("StreamTitle"))
return "";
String streamTitle = data.get("StreamTitle");
String artist = streamTitle.substring(streamTitle.indexOf("-")+1);
return artist.trim();
}
public Map<String, String> getMetadata() throws IOException {
if (metadata == null) {
refreshMeta();
}
return metadata;
}
public void refreshMeta() throws IOException {
retreiveMetadata();
}
private void retreiveMetadata() throws IOException {
URLConnection con = streamUrl.openConnection();
con.setRequestProperty("Icy-MetaData", "1");
con.setRequestProperty("Connection", "close");
con.setRequestProperty("Accept", null);
con.connect();
int metaDataOffset = 0;
Map<String, List<String>> headers = con.getHeaderFields();
InputStream stream = con.getInputStream();
if (headers.containsKey("icy-metaint")) {
// Headers are sent via HTTP
metaDataOffset = Integer.parseInt(headers.get("icy-metaint").get(0));
} else {
// Headers are sent within a stream
StringBuilder strHeaders = new StringBuilder();
char c;
while ((c = (char)stream.read()) != -1) {
strHeaders.append(c);
if (strHeaders.length() > 5 && (strHeaders.substring((strHeaders.length() - 4), strHeaders.length()).equals("\r\n\r\n"))) {
// end of headers
break;
}
}
// Match headers to get metadata offset within a stream
Pattern p = Pattern.compile("\\r\\n(icy-metaint):\\s*(.*)\\r\\n");
Matcher m = p.matcher(strHeaders.toString());
if (m.find()) {
metaDataOffset = Integer.parseInt(m.group(2));
}
}
// In case no data was sent
if (metaDataOffset == 0) {
isError = true;
return;
}
// Read metadata
int b;
int count = 0;
int metaDataLength = 4080; // 4080 is the max length
boolean inData = false;
StringBuilder metaData = new StringBuilder();
// Stream position should be either at the beginning or right after headers
while ((b = stream.read()) != -1) {
count++;
// Length of the metadata
if (count == metaDataOffset + 1) {
metaDataLength = b * 16;
}
if (count > metaDataOffset + 1 && count < (metaDataOffset + metaDataLength)) {
inData = true;
} else {
inData = false;
}
if (inData) {
if (b != 0) {
metaData.append((char)b);
}
}
if (count > (metaDataOffset + metaDataLength)) {
break;
}
}
// Set the data
metadata = IcyStreamMeta.parseMetadata(metaData.toString());
// Close
stream.close();
}
public boolean isError() {
return isError;
}
public URL getStreamUrl() {
return streamUrl;
}
public void setStreamUrl(URL streamUrl) {
this.metadata = null;
this.streamUrl = streamUrl;
this.isError = false;
}
public static Map<String, String> parseMetadata(String metaString) {
Map<String, String> metadata = new HashMap();
String[] metaParts = metaString.split(";");
Pattern p = Pattern.compile("^([a-zA-Z]+)=\\'([^\\']*)\\'$");
Matcher m;
for (int i = 0; i < metaParts.length; i++) {
m = p.matcher(metaParts[i]);
if (m.find()) {
metadata.put((String)m.group(1), (String)m.group(2));
}
}
return metadata;
}
}
Use prepareAsync() and not prepare(). See the documentation here: http://developer.android.com/guide/topics/media/mediaplayer.html#preparingasync
I need to prevent against lazy load in my custom list-view. so i found that scrollview onscroll listner are helpfull over there i have tryed it but not getting success to implement this functionality.
Code:
lviewAdapter = new ListViewAdapter(SaxParser2.this, Arr_ActivityName, Arr_AudioScript,Arr_RequestID,Arr_FolderPath,Arr_RequestTo);
lview.setOnScrollListener(SaxParser2.this);
#Override
public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
lview.setAdapter(lviewAdapter);
}
#Override
public void onScrollStateChanged(AbsListView arg0, int arg1) {
// TODO Auto-generated method stub
}
here is my BaseAdapter
package com.RecordingApp;
import it.sauronsoftware.ftp4j.FTPClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.AsyncTask;
import android.os.CountDownTimer;
import android.os.Environment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.Sharedpreferance.GMailSender;
public class ListViewAdapter extends BaseAdapter {
public static Activity context;
String title[];
String description[];
String RequestId[];
String Folderpath[];
String RequestTo[];
boolean b_Flag_Record_or_not = false;
boolean b_upload_or_not = false;
boolean start_or_not = false;
boolean start_play = false;
boolean upload_or_not = false;
boolean b_play_or_not = false;
boolean isplaying2 = false;
Thread welcomeThread,welcomeThread2;
int glob_position;
MediaPlayer mPlayer2;
int flag_stop_position;
AudioRecorder recorder;
AnimationDrawable frameAnimation, frameAnimation_play;
private static String mFileName = null;
private MediaRecorder mRecorder = null;
private MediaPlayer mPlayer = null;
Recording login = new Recording();
MediaPlayer MP_completeRequest = new MediaPlayer();
public ListViewAdapter(Activity context, String[] title,
String[] description, String[] req_id, String[] FolderPath,
String[] Arr_RequestTo) {
super();
this.context = context;
this.title = title;
this.description = description;
this.RequestId = req_id;
this.Folderpath = FolderPath;
this.RequestTo = Arr_RequestTo;
}
public int getCount() {
// TODO Auto-generated method stub
return title.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
private class ViewHolder {
TextView txtViewTitle;
TextView txtViewDescription;
Button record, stop, play, upload;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
glob_position = position;
if (convertView == null) {
convertView = inflater.inflate(R.layout.listitem_row, null);
holder = new ViewHolder();
holder.txtViewTitle = (TextView) convertView
.findViewById(R.id.textView1);
holder.txtViewDescription = (TextView) convertView
.findViewById(R.id.textView2);
holder.record = (Button) convertView.findViewById(R.id.record);
holder.stop = (Button) convertView.findViewById(R.id.stop);
holder.play = (Button) convertView.findViewById(R.id.play1);
holder.upload = (Button) convertView
.findViewById(R.id.audio_upload);
holder.record.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (isplaying2 == true) {
} else {
if (b_Flag_Record_or_not == true) {
} else {
try {
holder.record.setBackgroundResource(R.drawable.record_green);
b_Flag_Record_or_not = true;
b_play_or_not = true;
flag_stop_position = position;
AuthHandler dataHandler = new AuthHandler();
AuthDataset dataset = dataHandler
.getParsednewJobdtl_DataSet();
// Login l = new Login();
String str_useid = RequestTo[position];
recorder = new AudioRecorder(
"/audiometer/shanesh"
+ RequestId[position] + "-"
+ str_useid);
start_or_not = true;
recorder.start();
Toast.makeText(context, "Recording Started",
Toast.LENGTH_LONG).show();
CountDownTimer countDowntimer = new CountDownTimer(
120000000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
try {
Toast.makeText(
context,
"Stop recording Automatically ",
Toast.LENGTH_LONG).show();
recorder.stop();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
countDowntimer.start();
} catch (IOException e) {
gotoGmail(e);
} catch (Exception e) {
gotoGmail(e);
}
}
}
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
try {
Typeface face = Typeface.createFromAsset(context.getAssets(),
"fonts/tahoma.ttf");
holder.txtViewTitle.setTypeface(face);
holder.txtViewTitle.setText(title[position]);
holder.txtViewDescription.setText(description[position]);
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
holder.stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
if (isplaying2 == true) {
mPlayer2.stop();
isplaying2 = false;
} else {
holder.record.setBackgroundResource(R.drawable.page7_15);
if (flag_stop_position == position) {
b_Flag_Record_or_not = false;
if (start_or_not == true) {
b_play_or_not = false;
recorder.stop();
upload_or_not = true;
start_play = true;
Toast.makeText(context, "Stoped Recording",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context,
" Please Start recording ",
Toast.LENGTH_LONG).show();
}
} else {
}
}
} catch (Exception e) {
gotoGmail(e);
}
}
});
holder.play.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String temp = SaxParser2.str_completeORpendingFlag;
if (temp.equalsIgnoreCase("c")) {
try {
final MediaPlayer mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(Folderpath[position]);
mPlayer.prepare();
final int welcomeScreenDisplay = mPlayer
.getDuration();
welcomeThread = new Thread() {
int wait = 0;
#Override
public void run() {
try {
isplaying2 = true;
mPlayer.start();
while (wait < welcomeScreenDisplay) {
sleep(100);
wait += 100;
}
} catch (Exception e) {
} finally {
isplaying2 = false;
}
}
};
welcomeThread.start();
} catch (Exception e) {
gotoGmail(e);
}
} catch (Exception e) {
gotoGmail(e);
}
} else if (temp.equalsIgnoreCase("p")) {
try {
if (b_play_or_not == true) {
} else {
String str_useid = RequestTo[position];
java.io.File file = new java.io.File(Environment
.getExternalStorageDirectory()
+ "/audiometer/", "shanesh"
+ RequestId[position] + "-" + str_useid
+ ".amr");
if (file.exists()) {
Toast.makeText(context, "Playing",
Toast.LENGTH_LONG).show();
mPlayer2 = new MediaPlayer();
try {
mPlayer2.setDataSource(Environment
.getExternalStorageDirectory()
+ "/audiometer/shanesh"
+ RequestId[position]
+ "-"
+ str_useid + ".amr");
mPlayer2.prepare();
mPlayer2.start();
isplaying2 = true;
final int welcomeScreenDisplay = mPlayer2
.getDuration();
/**
* create a thread to show splash up to
* splash time
*/
welcomeThread = new Thread() {
int wait = 0;
#Override
public void run() {
try {mPlayer2.prepare();
while (wait < welcomeScreenDisplay) {
sleep(100);
wait += 100;
}
} catch (Exception e) {
} finally {
welcomeThread2 = new Thread() {
int wait = 0;
#Override
public void run() {
try {
mPlayer2.start();
while (wait < welcomeScreenDisplay) {
sleep(100);
wait += 100;
}
} catch (Exception e) {
} finally {
// frameAnimation_play.stop();
isplaying2 = false;
}
}
};
welcomeThread2.start();
}
}
};
welcomeThread.start();
} catch (Exception e) {
gotoGmail(e);
}
} else {
Toast.makeText(context, " File Not Found ",
Toast.LENGTH_LONG).show();
}
}
} catch (Exception e) {
gotoGmail(e);
}
}
}
});
holder.upload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
glob_position = position;
// String str_useid = RequestTo[position];
if (upload_or_not == true) {
try {
new xyz().execute();
} catch (Exception e) {
gotoGmail(e);
}
}
}
});
return convertView;
}
private class xyz extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(context);
protected void onPreExecute() {
try {
this.dialog.setMessage("Uploading...Please Wait..");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
this.dialog.show();
// put your code which preload with processDialog
} catch (Exception e) {
gotoGmail(e);
}
}
#Override
protected Void doInBackground(Void... arg0) {
for (int i = 0; i < 100000; i++) {
}
it.sauronsoftware.ftp4j.FTPClient con = new it.sauronsoftware.ftp4j.FTPClient();
try {
String str_useid = RequestTo[glob_position];
con.connect("URL");
con.login("as", "asdasd");
con.changeDirectory("/rangam/RequestContent/audio");
con.setPassive(true);
con.setType(FTPClient.TYPE_BINARY);
con.upload(new java.io.File(Environment
.getExternalStorageDirectory()
+ "/audiometer/shanesh"
+ RequestId[glob_position] + "-" + str_useid + ".amr"));
String filename = "/shanesh" + RequestId[glob_position] + "-"
+ str_useid + ".amr";
con.logout();
con.disconnect(true);
String MachineName = Machinelist.str_Machinename;
sendFlagToServer(RequestId[glob_position], filename,
MachineName);
} catch (Exception e) {
gotoGmail(e);
}
return null;
}
protected void onPostExecute(final Void unused) {
if (this.dialog.isShowing()) {
try {
this.dialog.dismiss();
AlertDialog.Builder alertbox = new AlertDialog.Builder(
context);
alertbox.setTitle("Message");
alertbox.setMessage(":: Uploaded Successfully ::");
alertbox.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
Intent intent_request = new Intent(context,
SaxParser2.class);
intent_request.putExtra("value", Machinelist.str_UIDValue);
intent_request.putExtra("machineName",
Machinelist.str_Machinename);
intent_request.putExtra("captureBack_or_not", 2);
context.startActivity(intent_request);
context.finish();
}
});
alertbox.show();
} catch (Exception e) {
gotoGmail(e);
}
}
}
}
private void sendFlagToServer(String requestID, String filename,
String machineName) {
HttpURLConnection connection;
OutputStreamWriter request = null;
String MachineName = Machinelist.str_Machinename;
URL url = null;
String parameters = "RequestID=" + requestID + "&FileName=" + filename
+ "&MachineName=" + MachineName + "&RequestType=A";
try {
url = new URL(
"URL");
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(
connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
reader.close();
} catch (Exception e) {
gotoGmail(e);
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
try {
context.finish();
} catch (Exception e) {
gotoGmail(e);
}
}
return false;
}
void gotoGmail(Exception e) {
Writer writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
e.printStackTrace(printWriter);
String s = writer.toString();
}
}
Ok,
So first you'll have to define "what is the number of views I'd need to load in order my user not to see that it's lazy loading ?" :
Let's say, you'd want to load 20 rows...
Now in you onscroll, or wherever you want but somewhere like on scroll or Adapter.getView, you'll have to know what is displayed on screen at the moment... Let me explain :
I want to load 20 rows so my user doesn't notice,
I am display 10 of them
and 10 of them are just hidden (not displayed if the guy doesn't scroll).
Now, I wan't to load 10 more when the guy just hit my 15th row
What could be the best way to do that ???
Humm, let's see, trying to find something that returns the (ABSOLUTE) number of the last row displayed on screen - this could be a nice solution.
An otehr solution could be that your 10 or 15th row is the first one displayed on screen ?
etc, etc...
I think stuffs like that should do the trick. ;)
Here is a sample I grabbed from Net. It is loading the items by listening to the Scroll of the ListView . For sample it is loading dates in ListView. After reached the end position it will load next 15 dates. It is Never Ending List . You can modify the adapter to your custom adapter. The concept is:
You have set of data
Loading first n no of items
Set the scroll listener to the listview
If scroll reaches Last Visible Item in Listview , You trigger the worker thread to load additional m no of items.
Notify listview from an UI thread.
int itemsPerPage = 15;
boolean loadingMore = false;
ArrayList<String> myListItems;
ArrayAdapter<String> adapter;
//For test data :-)
Calendar d = Calendar.getInstance();
this.getListView().setOnScrollListener(new OnScrollListener(){
//useless here, skip!
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
//what is the bottom item that is visible
int lastInScreen = firstVisibleItem + visibleItemCount;
//is the bottom item visible & not loading more already ? Load more !
if((lastInScreen == totalItemCount) && !(loadingMore)){
Thread thread = new Thread(null, loadMoreListItems);
thread.start();
}
}
});
//Load the first 15 items
Thread thread = new Thread(null, loadMoreListItems);
thread.start();
}
//Runnable to load the items
private Runnable loadMoreListItems = new Runnable() {
#Override
public void run() {
//Set flag so we cant load new items 2 at the same time
loadingMore = true;
//Reset the array that holds the new items
myListItems = new ArrayList<String>();
//Get 15 new listitems
for (int i = 0; i < itemsPerPage; i++) {
//Fill the item with some bogus information
myListItems.add("Date: " + (d.get(Calendar.MONTH)+ 1) + "/" + d.get(Calendar.DATE) + "/" + d.get(Calendar.YEAR) );
// +1 day :-D
d.add(Calendar.DATE, 1);
}
//Done! now continue on the UI thread
runOnUiThread(returnRes);
}
};
//Since we cant update our UI from a thread this Runnable takes care of that!
private Runnable returnRes = new Runnable() {
#Override
public void run() {
//Loop thru the new items and add them to the adapter
if(myListItems != null && myListItems.size() > 0){
for(int i=0;i<myListItems.size();i++)
adapter.add(myListItems.get(i));
}
//Update the Application title
setTitle("Neverending List with " + String.valueOf(adapter.getCount()) + " items");
//Tell to the adapter that changes have been made, this will cause the list to refresh
adapter.notifyDataSetChanged();
//Done loading more.
loadingMore = false;
}
};
EDIT:
You can get tutorial and full project here
The problem is, the onPanChanged() method gets called twice causing the points to flash before they are plotted every time a user moves or pans around the map. What can I do to make the onPanChanged() method only get called once. In the code, I even try to turn off the listener and turn it back on when I exit the AsyncTask.
I would like you to share some of your thoughts and opinions.
// MapActivity
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
public class MapActivityNearby extends MapActivity implements EnhancedMapView.OnPanChangeListener {
private EnhancedMapView mv;
private static final String TAG = "MAPACTIVITY";
private static final String PREF_NAME = "cookie";
private double lat;
private double lng;
private ArrayList<MapItem> allCats;
private GeoPoint p;
private float latMin;
private float latMax;
private float longMin;
private float longMax;
private MapController mapControl;
private List<Overlay> mapOverlays;
private MyItemizedOverlay itemizedOverlay;
boolean waitTime = true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_nearby);
LinearLayout ll = (LinearLayout) findViewById(R.id.maplayout);
mv = new EnhancedMapView(this, "api_key");
mv.setClickable(true);
mv.setBuiltInZoomControls(true);
mv.setOnZoomChangeListener(new EnhancedMapView.OnZoomChangeListener() {
#Override
public void onZoomChange(MapView view, int newZoom, int oldZoom) {
Log.d("test", "zoom changed from " + oldZoom + " to " + newZoom);
}
});
ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
mv.setLayoutParams(lp);
ll.addView(mv);
SharedPreferences cookies = getSharedPreferences(PREF_NAME,
Context.MODE_PRIVATE);
lat = Double.parseDouble(cookies.getString("lat", "0"));
lng = Double.parseDouble(cookies.getString("lng", "0"));
GeoPoint p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
mapControl = mv.getController();
mapControl.setZoom(11);
mapControl.setCenter(p);
}
public void onResume()
{
super.onResume();
if (isNetworkAvailable(MapActivityNearby.this))
{
PlotPoints plot = new PlotPoints();
plot.execute(mv);
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(MapActivityNearby.this);
builder.setMessage("No network connection. Please try again when your within coverage area.")
.setTitle("Network Connection")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//close dialog
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
public void plotPoints(ArrayList<MapItem> i) {
mapOverlays = mv.getOverlays();
// first overlay
Drawable drawable;
drawable = getResources().getDrawable(R.drawable.marker);
itemizedOverlay = new MyItemizedOverlay(drawable, mv);
mapOverlays.add(itemizedOverlay);
for (MapItem x : i) {
GeoPoint point = new GeoPoint((int) (x.getLat() * 1E6),
(int) (x.getLng() * 1E6));
OverlayItem overlayItem = new OverlayItem(point,
x.getTitle(), x.getSubtitle());
itemizedOverlay.addOverlay(overlayItem);
}
GeoPoint point = new GeoPoint((int) (((latMin + latMax) * 1E6) / 2), (int) (((longMin + longMax) * 1E6) /2));
MapController mc = mv.getController();
mc.setCenter(point);
}
private class PlotPoints extends AsyncTask<EnhancedMapView, Void, Boolean> {
String result = "";
InputStream is;
#Override
protected void onPreExecute() {
turnOff();
}
#Override
protected Boolean doInBackground(EnhancedMapView...params) {
turnOff();
int maxCount = 100;
EnhancedMapView mapView = params[0];
for (int i = 0; i < maxCount; i++)
{
p = mapView.getMapCenter();
float latCenter = (float) (p.getLatitudeE6()) / 1000000;
float longCenter = (float) (p.getLongitudeE6()) / 1000000;
float latSpan = (float) (mapView.getLatitudeSpan()) / 1000000;
float longSpan = (float) (mapView.getLongitudeSpan()) / 1000000;
latMax = latCenter + (latSpan/2);
latMin = latCenter - (latSpan/2);
longMax = longCenter + (longSpan/2);
longMin = longCenter - (longSpan/2);
if (latMin == latMax)
{
try
{
Thread.sleep(80);
}
catch(InterruptedException e)
{
}
}
else
{
p = mapView.getMapCenter();
latCenter = (float) (p.getLatitudeE6()) / 1000000;
longCenter = (float) (p.getLongitudeE6()) / 1000000;
latSpan = (float) (mapView.getLatitudeSpan()) / 1000000;
longSpan = (float) (mapView.getLongitudeSpan()) / 1000000;
latMax = latCenter + (latSpan/2);
latMin = latCenter - (latSpan/2);
longMax = longCenter + (longSpan/2);
longMin = longCenter - (longSpan/2);
break;
}
}
log(latMin);
log(latMax);
try {
final String catURL = "url";
log(catURL.toString());
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(catURL);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("PHPSESSID", getCookie()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
result = convertStreamToString();
log(result);
allCats = new ArrayList<MapItem>();
JSONObject object = new JSONObject(result);
JSONArray temp = object.getJSONArray("l");
log("Starting download");
log(temp.length());
long start = System.currentTimeMillis();
for (int k = 0; k < temp.length(); k++) {
JSONObject j = temp.getJSONObject(k);
MapItem c = new MapItem();
c.setObject_id(j.getInt("object_id"));
c.setTitle(j.getString("title"));
c.setColor(j.getString("color"));
c.setLat(j.getDouble("lat"));
c.setLng(j.getDouble("lng"));
c.setSubtitle(j.getString("subtitle"));
allCats.add(c);
log(allCats.toString());
}
long end = System.currentTimeMillis();
log("Download Took: " + (end - start) / 1000 + " seconds.");
// log(allCats.toString());
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
#Override
protected void onPostExecute(Boolean results) {
// pBar.setVisibility(View.GONE);
plotPoints(allCats);
turnOn();
}
private String convertStreamToString() {
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
result.trim();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return result;
}
}
public String getCookie() {
String cookie = "";
SharedPreferences cookies = getSharedPreferences(PREF_NAME,
Context.MODE_PRIVATE);
if (cookies.contains("cookie")) {
cookie = cookies.getString("cookie", "null");
}
return cookie;
}
private void log(Object obj) {
Log.d(TAG, TAG + " :: " + obj.toString());
}
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
#Override
public void onPanChange(MapView view, GeoPoint newCenter, GeoPoint oldCenter) {
Log.d("test", "center changed from " + oldCenter.getLatitudeE6() + "," + oldCenter.getLongitudeE6() + " to " + newCenter.getLatitudeE6() + "," + newCenter.getLongitudeE6());
if(!mv.getOverlays().isEmpty())
{
mv.getOverlays().clear();
mv.postInvalidate();
}
if (isNetworkAvailable(MapActivityNearby.this))
{
PlotPoints log = new PlotPoints();
log.execute(mv);
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(MapActivityNearby.this);
builder.setMessage("No network connection. Please try again when your within coverage area.")
.setTitle("Network Connection")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//close dialog
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
public void turnOn ()
{
mv.setOnPanChangeListener(this);
}
public void turnOff ()
{
mv.setOnPanChangeListener(null);
}
}
// EnhancedMapView
import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
public class EnhancedMapView extends MapView {
public interface OnZoomChangeListener {
public void onZoomChange(MapView view, int newZoom, int oldZoom);
}
public interface OnPanChangeListener {
public void onPanChange(MapView view, GeoPoint newCenter, GeoPoint oldCenter);
}
private EnhancedMapView _this;
// Set this variable to your preferred timeout
private long events_timeout = 500L;
private boolean is_touched = false;
private GeoPoint last_center_pos;
private int last_zoom;
private Timer zoom_event_delay_timer = new Timer();
private Timer pan_event_delay_timer = new Timer();
private EnhancedMapView.OnZoomChangeListener zoom_change_listener;
private EnhancedMapView.OnPanChangeListener pan_change_listener;
public EnhancedMapView(Context context, String apiKey) {
super(context, apiKey);
_this = this;
last_center_pos = this.getMapCenter();
last_zoom = this.getZoomLevel();
}
public EnhancedMapView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public EnhancedMapView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void setOnZoomChangeListener(EnhancedMapView.OnZoomChangeListener l) {
zoom_change_listener = l;
}
public void setOnPanChangeListener(EnhancedMapView.OnPanChangeListener l) {
pan_change_listener = l;
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
if (ev.getAction() == 1) {
is_touched = false;
} else {
is_touched = true;
}
return super.onTouchEvent(ev);
}
#Override
public void computeScroll() {
super.computeScroll();
if (getZoomLevel() != last_zoom) {
// if computeScroll called before timer counts down we should drop it and start it over again
zoom_event_delay_timer.cancel();
zoom_event_delay_timer = new Timer();
zoom_event_delay_timer.schedule(new TimerTask() {
#Override
public void run() {
zoom_change_listener.onZoomChange(_this, getZoomLevel(), last_zoom);
last_zoom = getZoomLevel();
}
}, events_timeout);
}
// Send event only when map's center has changed and user stopped touching the screen
if (!last_center_pos.equals(getMapCenter()) && !is_touched) {
pan_event_delay_timer.cancel();
pan_event_delay_timer = new Timer();
try
{
pan_event_delay_timer.schedule(new TimerTask() {
#Override
public void run() {
try
{
pan_change_listener.onPanChange(_this, getMapCenter(), last_center_pos);
last_center_pos = getMapCenter();
}
catch (IllegalArgumentException e)
{
Log.v("IllegalArgumentException", e.toString());
}
catch (IllegalStateException e)
{
Log.v("IllegalStateException", e.toString());
}
catch (NullPointerException e)
{
Log.v("NullPointerException", e.toString());
}
}
}, events_timeout);
}
catch (IllegalArgumentException e)
{
Log.v("IllegalArgumentException", e.toString());
}
catch (IllegalStateException e)
{
Log.v("IllegalStateException", e.toString());
}
catch (NullPointerException e)
{
Log.v("NullPointerException", e.toString());
}
}
}
}
Why does this app stop answering then I press play? It sometimes show a "the application is not responding" but it works if I wait.
It works nice on my emulator, but not on my phone (or any other phone I tried).
All it does is streaming sound.
package comunicera.se;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.ListActivity;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ProgressBar;
import android.widget.TextView;
public class Godnattsaga extends ListActivity {
/** Called when the activity is first created. */
ListView list;
TextView spelandesSagqa;
//private ProgressDialog mProgressDialog;
ProgressBar myProgressBar;
int myProgress = 0;
MediaPlayer mp = new MediaPlayer();
String BASEURL = "http://godnattsaga.nu/sagor";
public static long glCurrentSaga = 0;
public static String giCode = null;
int giAntalSagor = 0;
int possWhenPaused = 0;
ProgressBar myBufferProgressBar;
TextView buffrarText;
int progress;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try
{
new Thread(buffer).start();
String lsSagor = getFileFromUrl(BASEURL+"/gratisSagor.txt");
final String[] laList = lsSagor.split("~");
giAntalSagor = laList.length;
//String saga = laList[0].replaceAll("#", "\n");
String[] laSaga = laList[0].split("#");
final String[] guiLaList = new String[giAntalSagor];
for (int i = 0; i < giAntalSagor; i++)
{
guiLaList[i] = laList[i].replaceAll("#", "\n");
}
changeSpelandesSaga(laSaga[0]);
setList (guiLaList);
ListView list = getListView();
list.setTextFilterEnabled(true);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String liCode = kop(id);
glCurrentSaga = id;
String[] laSaga = laList[(int) glCurrentSaga].split("#");
changeSpelandesSaga(laSaga[0]);
}
});
final Button button = (Button) findViewById(R.id.SpelaPause);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
selectDownloadOrPLay(laList);
}
});
glCurrentSaga = 0;
changeSpelandesSaga(laSaga[0]);
}
catch (Exception e)
{
changeSpelandesSaga("Check your connection, are you in flightmode?");
}
}
public void selectDownloadOrPLay(String[] laList) {
String[] laSaga = laList[(int) glCurrentSaga].split("#");
String url = BASEURL+"/gratis/"+laSaga[0].replaceAll(" ", "_")+".mp3";
if (mp.isPlaying())
{
mp.pause();
possWhenPaused=mp.getCurrentPosition();
}
else if (possWhenPaused != 0)
{
mp.start();
}
else
{
startSaga (url);
}
}
private String kop(long id)
{
mp.pause();
return "gratis";
}
public void setList (String[] laList)
{
/*
*
final String[] lAList = new String[3];
lAList[0] = "Saga 1 \n";
lAList[1] = "Saga 2 \n";
lAList[2] = "Saga 3";
setList (lAList);
*
*/
setContentView(R.layout.main);
ArrayAdapter<String> appointmentList = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, laList);
list=(ListView)findViewById(android.R.id.list);
list.setAdapter(appointmentList);
}
public void changeSpelandesSaga(String sagaRubrik)
{
possWhenPaused = 0;
TextView t = new TextView(this);
t=(TextView)findViewById(R.id.spelandesSaga);
t.setText(Html.fromHtml("<b>"+sagaRubrik+"</b>"));
}
private void startSaga(String url)
{
try {
mp.reset();
mp.setDataSource(url);
mp.prepare();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
myProgressBar=(ProgressBar)findViewById(R.id.mProgressDialog);
new Thread(myThread).start();
}
private Runnable myThread = new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
while (myProgress<100){
try{
myHandle.sendMessage(myHandle.obtainMessage());
Thread.sleep(1000);
}
catch(Throwable t){
}
}
}
Handler myHandle = new Handler(){
double poss = 0.0;
double sagaleng = 0.0;
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
poss = mp.getCurrentPosition();
sagaleng = mp.getDuration();
progress = (int) ((int)poss / sagaleng * 100);
myProgress = progress;
myProgressBar.setProgress(progress);
}
};
};
public static String getFileFromUrl(String url)
{
InputStream content = null;
try
{
HttpGet httpGet = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
// Execute HTTP Get Request
HttpResponse response = httpclient.execute(httpGet);
content = response.getEntity().getContent();
}
catch (Exception e)
{
showNoConnection ();
return null;
}
BufferedReader rd = new BufferedReader(new InputStreamReader(content), 4096);
String line;
StringBuilder sb = new StringBuilder();
try {
while ((line = rd.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
rd.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sb.toString();
}
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
boolean connected = cm.getActiveNetworkInfo().isConnectedOrConnecting();
return connected;
}
private static void showNoConnection()
{
}
private Runnable buffer = new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
while (myProgress<100){
try{
myHandle.sendMessage(myHandle.obtainMessage());
Thread.sleep(1000);
}
catch(Throwable t)
{
}
}
}
Handler myHandle = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
//SpelaPause.setImageURI("pauseicon");
myBufferProgressBar = (ProgressBar)findViewById(R.id.mBuffrar);
TextView bufferText = (TextView)findViewById(R.id.buffrarText);
if (mp.isPlaying() && progress == 0)
{
myBufferProgressBar.setVisibility(View.VISIBLE);
bufferText.setVisibility(View.VISIBLE);
}
else
{
myBufferProgressBar.setVisibility(View.INVISIBLE);
bufferText.setVisibility(View.INVISIBLE);
}
}
};
};
}
If your application uses internet, it is possible, that the phone has worse connection than your comp. For example, if they both run on the SAME WiFi, at the same point, phones are connected MUCH worse than PC. Slower connection - you have to wait...
Read http://developer.android.com/guide/practices/design/responsiveness.html and http://developer.android.com/guide/practices/design/performance.html - VERY useful. For example, you will know the name of your problem - bad responsiveness (not performance) - for better further searches. :-)
All long-lasting tasks should be run in separate thread, not in UI thread. You call getFileFromUrl(..) from onCreate(..) method. This cause hangings.
I recommend you not to do any time consuming task in onCreate(..) method. In general an activity won't be shown till onCreate(..) is finished.
You are using getFileFromUrl in your onCreate method. Your method just performs the download action, which in case could last some time. You should always move long running tasks into it's own thread and notify the UI thread only.
Consider never running big logic in the UI thread, the UI thread should only be responsible for UI stuff.
To download a file in an async manner try to use the AsyncTask: http://developer.android.com/reference/android/os/AsyncTask.html
This code works, without responsiveness problems. But the buffering takes to long time so I need another solution.
I'm posting some code if someone else have the same problem
package comunicera.se;
import java.io.IOException;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class GodnattsagaTest1 extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button button = (Button) findViewById(R.id.SpelaPause);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
selectDownloadOrPLay();
}
});
}
public void selectDownloadOrPLay() {
Toast.makeText(getApplicationContext(), "Before ... ", Toast.LENGTH_SHORT).show();
Saga.startSaga ();
Toast.makeText(getApplicationContext(), "after ... ", Toast.LENGTH_SHORT).show();
}
}
class Saga
{
static MediaPlayer mp = new MediaPlayer();
static void startSaga()
{
new Thread(spelaSaga).start();
}
private static Runnable spelaSaga = new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
try {
mp.reset();
mp.setDataSource("http://godnattsaga.nu/sagor/gratis/Fisken.mp3");
mp.prepare();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
}
};
}
I believe it has something to do with the progress bar you use. I use one and it slows my app. Not sure if the progress bar must slow the app or there is another way to avoid this though.