I'm trying to implement subtitles to videoview. I've used this example project :
package com.example.media.timedtexttest;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Locale;
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnTimedTextListener;
import android.media.MediaPlayer.TrackInfo;
import android.media.TimedText;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends Activity implements OnTimedTextListener {
private static final String TAG = "TimedTextTest";
private TextView txtDisplay;
private static Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtDisplay = (TextView) findViewById(R.id.txtDisplay);
MediaPlayer player = MediaPlayer.create(this, R.raw.video);
try {
player.addTimedTextSource(getSubtitleFile(R.raw.sub),
MediaPlayer.MEDIA_MIMETYPE_TEXT_SUBRIP);
int textTrackIndex = findTrackIndexFor(
TrackInfo.MEDIA_TRACK_TYPE_TIMEDTEXT, player.getTrackInfo());
if (textTrackIndex >= 0) {
player.selectTrack(textTrackIndex);
} else {
Log.w(TAG, "Cannot find text track!");
}
player.setOnTimedTextListener(this);
player.start();
} catch (Exception e) {
e.printStackTrace();
}
}
private int findTrackIndexFor(int mediaTrackType, TrackInfo[] trackInfo) {
int index = -1;
for (int i = 0; i < trackInfo.length; i++) {
if (trackInfo[i].getTrackType() == mediaTrackType) {
return i;
}
}
return index;
}
private String getSubtitleFile(int resId) {
String fileName = getResources().getResourceEntryName(resId);
File subtitleFile = getFileStreamPath(fileName);
if (subtitleFile.exists()) {
Log.d(TAG, "Subtitle already exists");
return subtitleFile.getAbsolutePath();
}
Log.d(TAG, "Subtitle does not exists, copy it from res/raw");
// Copy the file from the res/raw folder to your app folder on the
// device
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = getResources().openRawResource(resId);
outputStream = new FileOutputStream(subtitleFile, false);
copyFile(inputStream, outputStream);
return subtitleFile.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
} finally {
closeStreams(inputStream, outputStream);
}
return "";
}
private void copyFile(InputStream inputStream, OutputStream outputStream)
throws IOException {
final int BUFFER_SIZE = 1024;
byte[] buffer = new byte[BUFFER_SIZE];
int length = -1;
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
}
// A handy method I use to close all the streams
private void closeStreams(Closeable... closeables) {
if (closeables != null) {
for (Closeable stream : closeables) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
#Override
public void onTimedText(final MediaPlayer mp, final TimedText text) {
if (text != null) {
handler.post(new Runnable() {
#Override
public void run() {
int seconds = mp.getCurrentPosition() / 1000;
txtDisplay.setText("[" + secondsToDuration(seconds) + "] "
+ text.getText());
}
});
}
}
// To display the seconds in the duration format 00:00:00
public String secondsToDuration(int seconds) {
return String.format("%02d:%02d:%02d", seconds / 3600,
(seconds % 3600) / 60, (seconds % 60), Locale.US);
}
}
and created exactly the same implementation and it somehow works, but if i stop video and continue subtitle doesn't continue or if i seek video to some time subtitle doesn't continue too.
What i have tried:
Every time before player.start() i set player.selectTrack(textTrackIndex);
I've tried to reregister listener when i'm doing player.start(); player.setOnTimedTextListener(this);
Please help i've spent 4 days on subtitle features... If you have some project example or snippet it would be nice :)
we have the same problem and we must implements OnSeekCompleteListener even if you nothing to do into override method
it's our code:
#Override
public void onSeekComplete(MediaPlayer mediaPlayer) {
}
and it work !!!
I hope that help you
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 sending some data to an android application over UDP. Therefore i created the following UDPReceiver-Class:
package com.example.urowatch;
import java.net.*;
import java.nio.ByteBuffer;
import java.io.*;
public class UDPReceiver extends Thread
{
private DatagramSocket m_Socket;
private int m_BufferSize;
private Boolean m_End = false;
private int m_TotalLength;
private int m_Received;
private byte[] m_Buffer;
private byte[] m_Result;
private Boolean m_IsNewResult = false;
private float m_Progress;
private int m_ImageCount = 0;
private int m_FrameErrors = 0;
public UDPReceiver(String name, int port, int bufferSize) throws IOException
{
super(name);
m_Socket = new DatagramSocket(port);
m_BufferSize = bufferSize;
m_Socket.setBroadcast(true);
m_Socket.setReceiveBufferSize(m_BufferSize);
}
public void run()
{
while(!m_End)
{
try
{
byte[] buf = new byte[m_BufferSize];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
m_Socket.receive(packet);
ProcessData(packet);
}
catch (IOException e)
{
if (!m_Socket.isClosed())
e.printStackTrace();
}
}
}
private void ProcessData(DatagramPacket packet)
{
if (packet.getLength() == 4)
{
ByteBuffer bb = ByteBuffer.wrap(packet.getData());
m_TotalLength = bb.getInt();
if (m_Received != 0)
m_FrameErrors++;
m_Received = 0;
m_Buffer = new byte[m_TotalLength];
}
else if (m_Buffer != null && m_Received != m_TotalLength)
{
int length = packet.getLength();
System.arraycopy(packet.getData(), 0, m_Buffer, m_Received, length);
m_Received += length;
m_Progress = 100 * (float)m_Received/(float)m_TotalLength;
if (m_Received == m_TotalLength)
{
m_Result = new byte[m_TotalLength];
System.arraycopy(m_Buffer, 0, m_Result, 0, m_TotalLength);
m_IsNewResult = true;
m_ImageCount++;
m_Received = 0;
}
}
}
public Boolean IsNewResult()
{
return m_IsNewResult;
}
public byte[] GetResult()
{
m_IsNewResult = false;
return m_Result;
}
public float GetProgress()
{
return m_Progress;
}
public float GetRatio()
{
return 100 * (float)m_ImageCount / (float)m_FrameErrors;
}
public void stopServer()
{
m_End = true;
if (m_Socket != null)
m_Socket.close();
}
}
And i am using this class like this:
package com.example.urowatch;
import java.io.IOException;
import java.text.DecimalFormat;
import android.os.*;
import android.app.Activity;
import android.app.AlertDialog;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v4.app.NavUtils;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.os.Build;
public class LiveActivity extends Activity {
private static ImageView m_ImageView1;
private static TextView m_TextView1;
private static DecimalFormat m_DF;
private static Context m_Context;
private UDPReceiver m_Receiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_live);
// Show the Up button in the action bar.
setupActionBar();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
m_ImageView1 = (ImageView)findViewById(R.id.imageView1);
m_TextView1 = (TextView)findViewById(R.id.textView1);
m_Context = this;
m_DF = new DecimalFormat("00.00");
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.live, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
private static Handler MyHandler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
if (msg.what == 100)
{
float[] infos = (float[])msg.obj;
m_TextView1.setText("Empfange Bild: " + m_DF.format(infos[0]) + "% (FrameErrors: " + m_DF.format(infos[1]) + "%)");
}
else if (msg.what == 101)
{
byte[] b = (byte[])msg.obj;
m_TextView1.setText("Empfange Bild: 100,00%");
m_ImageView1.setImageBitmap(BitmapFactory.decodeByteArray(b, 0, b.length));
}
else if (msg.what == 102)
{
AlertDialog.Builder b = new AlertDialog.Builder(m_Context);
b.setTitle("Fehler");
b.setMessage("Es ist folgende Exception aufgetreten:\n" + (Exception)msg.obj);
b.setNeutralButton("OK", null);
b.show();
}
}
};
#Override
public void onBackPressed() {
super.onBackPressed();
if (m_Receiver != null)
m_Receiver.stopServer();
finish();
}
#Override
public void onPause()
{
m_Receiver.stopServer();
super.onPause();
}
#Override
protected void onResume()
{
try {
m_Receiver = new UDPReceiver("UDPReceiver", 5678, 1024);
m_Receiver.start();
} catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setTitle("Fehler");
b.setMessage("Es ist folgende Exception aufgetreten:\n" + e1);
b.setNeutralButton("OK", null);
b.show();
}
// Thread thread = new Thread()
// {
// #Override
// public void run()
// {
// while(true)
// {
// try {
//sleep(250);
Toast.makeText(getBaseContext(), "Runing Thread", Toast.LENGTH_SHORT).show();
Update();
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// MyHandler.sendMessage(MyHandler.obtainMessage(102, e));
// }
// }
// }
// };
// thread.start();
super.onResume();
}
public void buttonClick(View v)
{
Update();
}
private void Update()
{
if (m_Receiver != null)
{
if (m_Receiver.IsNewResult())
{
byte[] b = m_Receiver.GetResult();
MyHandler.sendMessage(MyHandler.obtainMessage(101, b));
}
else
{
float[] infos = new float[2];
infos[0] = m_Receiver.GetProgress();
infos[1] = m_Receiver.GetRatio();
MyHandler.sendMessage(MyHandler.obtainMessage(100, infos));
}
}
}
}
As you see i want to check the status of the UDPReceiver-Object (Is there a new complete byte[] ready?) by a thread. To update the GUI, the thread has to send a Message to MyHandler which will update the GUI.
In the moment i have to to click a button to raise the buttonClick-Event. Later on i want to do this in the commented thread-structure.
Now, here's my problem:
I start the Activity and everything works fine. Then i am starting to send ONE packet manually with my UDP-Sender (which works, i validated it with a C#-UDP-Receiver). The first packet get received fine. Then i send the second packet which get received, too. But from now on, my breakpoint at m_Socket.receive(packet); wont get hit anymore!
I have NO idea what this behaviour causes and it is very important for me to make this application work.
Please, if you have ANY Idea or just a guess, please let me know.
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
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