Updating tables in SQL Server from an Android app - android

I am currently developing an Android app that gets details from an SQL Server table. Thanks to everyone who has helped previously with my understanding of AsyncTasks and JSON, I can now retrieve objects. However, my attempt at updating tables from an Android device is not so smooth.
Firstly, I'll begin with the table:
I have a JobStatus table that is populated by a trigger that runs as a new record is entered into the Jobs table. When the trigger is run, these 4 columns are populated, namely:-
The JobStatusID
The JobID
QLSJobID
JobType
The remaining 4 however, are null by default and are expected to be updated through the Android app operations. They are:-
Latitude
Longitude
TimeComplete
DateComplete
I have adapted a WCF web service obtained from here to do the operations. It is essentially a POST update operation.
Now, for the Android code. Essentially, what happens at the Android app is that a JobStatus entry is updated only when the Save/Sign button is captured. For that to happen, the user must input their name and sign for a Job for all the information to be sent back to the JobStatus table. Here is the code:
package com.signonglass;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONStringer;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore.Images;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class CaptureSignature extends Activity implements LocationListener
{
private final static String getJobURI = "http://192.168.0.105:8095/CentralMonitoring/CentralMonitor.svc/getJobStatus/";
private final static String jobURI = "http://192.168.0.105:8095/CentralMonitoring/CentralMonitor.svc/UpdateJobStatus";
final Date currentTime = new Date();
final SimpleDateFormat sdf = new SimpleDateFormat("EEE, MMM d, yyyy HH:mm:ss a z");
//Live Connections
//private final static String jobURI = "http://192.168.14.9:8092/CentralMonitoring/CentralMonitor.svc/UpdateJobStatus";
//private final static String getJobURI = "http://192.168.14.9:8092/CentralMonitoring/CentralMonitor.svc/getJobStatus/";
JSONStringer jobStatToUpdate;
LinearLayout mContent;
signature mSignature;
Button mClear, mGetSign, mCancel;
public static String tempDir;
public int count = 1;
public String current = null;
private Bitmap mBitmap;
View mView;
File mypath;
//additional variables for capturing details
Consignments cObj;
public Handler mHandler;
JobStatus js = new JobStatus();
JobStatus jsUpdate;
double latitude;
double longitude;
String datetime;
TextView tvLoc;
Location location;
String transAdd;
private String uniqueId;
private EditText yourName;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.signature);
cObj = (Consignments)this.getIntent().getSerializableExtra("Consignment");
//tempDir = Environment.getExternalStorageDirectory() + "/" + getResources().getString(R.string.external_dir) + "/";
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir(getResources().getString(R.string.external_dir), Context.MODE_PRIVATE);
prepareDirectory();
Calendar c = Calendar.getInstance();
c.setTimeZone(TimeZone.getDefault());
uniqueId = cObj.getJobType() + Integer.toString(cObj.getConsignmentID());
current = uniqueId + ".jpg";
mypath = new File(directory, current);
//Control Properties
mContent = (LinearLayout) findViewById(R.id.signing);
mSignature = new signature(this, null);
mSignature.setBackgroundColor(Color.WHITE);
mContent.addView(mSignature, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
mClear = (Button)findViewById(R.id.clear);
mGetSign = (Button)findViewById(R.id.getsign);
mGetSign.setEnabled(false);
mCancel = (Button)findViewById(R.id.cancel);
mView = mContent;
yourName = (EditText)findViewById(R.id.yourName);
/* Use the LocationManager class to obtain GPS locations */
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = mlocManager.getBestProvider(criteria, true);
location = mlocManager.getLastKnownLocation(provider);
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, CaptureSignature.this);
tvLoc = (TextView)findViewById(R.id.textView1);
tvLoc.setText("Latitude: "+ location.getLatitude() +", Longitude: "+ location.getLongitude());
mClear.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Log.v("log_tag", "Panel Cleared");
mSignature.clear();
mGetSign.setEnabled(false);
}
});
mGetSign.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Log.v("log_tag", "Panel Saved");
boolean error = captureSignature();
if(!error)
{
new updateJobStatus().execute(js);
mView.setDrawingCacheEnabled(true);
mSignature.save(mView);
Bundle b = new Bundle();
b.putString("status", "done");
Intent intent = new Intent();
intent.putExtras(b);
setResult(RESULT_OK,intent);
finish();
}
}
});
//Cancel method - to create pop up button
mCancel.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Log.v("log_tag", "Panel Canceled");
Bundle b = new Bundle();
b.putString("status", "cancel");
Intent intent = new Intent();
intent.putExtras(b);
setResult(RESULT_OK,intent);
finish();
}
});
new getJobStatus().execute(uniqueId);
}
public class getJobStatus extends AsyncTask<String, String, JobStatus>
{
private ProgressDialog progressDialog = new ProgressDialog(CaptureSignature.this);
InputStream inputStream = null;
String theString = "";
StringBuilder builder;
protected void onPreExecute()
{
progressDialog.setMessage("Getting " + uniqueId +" to be updated...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener()
{
public void onCancel(DialogInterface arg0)
{
getJobStatus.this.cancel(true);
}
});
}
#Override
protected JobStatus doInBackground(String... params)
{
try
{
DefaultHttpClient client = new DefaultHttpClient();
String theString = new String("");
//http get request
HttpGet request = new HttpGet(getJobURI + cObj.getJobType() + cObj.getConsignmentID());
//set the hedear to get the data in JSON format
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
//get the response
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null)
{
builder.append(line);
}
is.close();
theString = builder.toString();
JSONObject jsObj = new JSONObject(theString);
JSONArray jstat = jsObj.getJSONArray("getJobStatusResult");
for(int i = 0; i < jstat.length(); i++)
{
JSONObject jst = jstat.getJSONObject(i);
js.JobStatusID = jst.getInt("JobStatusID");
js.JobID = jst.getInt("JobID");
js.JobType = jst.getString("jobType");
js.QlsJobID = jst.getInt("qlsJobID");
/*js.DateComplete = jst.getString("dateComplete");
js.TimeComplete = jst.getString("timeComplete");
js.Latitude = jst.getDouble("latitude");
js.Longitude = jst.getDouble("longitude");*/
}
}
catch(Exception e)
{
e.printStackTrace();
}
return js;
}
protected void onPostExecute(JobStatus jobStatus)
{
this.progressDialog.dismiss();
jsUpdate = js;
}
}
public class updateJobStatus extends AsyncTask<JobStatus, String, JSONStringer>
{
private ProgressDialog progressDialog = new ProgressDialog(CaptureSignature.this);
InputStream inputStream = null;
String theString = "";
StringBuilder builder;
protected void onPreExecute()
{
progressDialog.setMessage("Updating " + uniqueId +"...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener()
{
public void onCancel(DialogInterface arg0)
{
updateJobStatus.this.cancel(true);
}
});
}
#Override
protected JSONStringer doInBackground(JobStatus... arg0)
{
HttpPut request = new HttpPut(jobURI);
try
{
sdf.setTimeZone(TimeZone.getTimeZone("AEST"));
jobStatToUpdate = new JSONStringer()
.object()
.key("JobStatusID").value(js.getJobStatusID())
.key("JobID").value(js.getJobID())
.key("dateComplete").value(js.getDate())
.key("latitude").value(js.getLat())
.key("longitude").value(js.getClass())
.key("timeComplete").value(js.getTime())
.key("qlsjobID").value(js.getQLSID())
.endObject();
StringEntity entity = new StringEntity(jobStatToUpdate.toString());
request.setEntity(entity);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
Log.d("WebInvoke", "Saving : " + response.getStatusLine().getStatusCode());
}
catch (Exception e)
{
e.printStackTrace();
}
return jobStatToUpdate;
}
}
#Override
protected void onDestroy()
{
//Log.w("GetSignature", "onDestory");
//super.onDestroy();
}
private boolean captureSignature()
{
boolean error = false;
String errorMessage = "";
if(yourName.getText().toString().equalsIgnoreCase(""))
{
errorMessage = errorMessage + "Please enter your Name\n";
error = true;
}
if(error)
{
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP, 105, 50);
toast.show();
}
return error;
}
private boolean prepareDirectory()
{
try
{
if (makedirs())
{
return true;
}
else
{
return false;
}
}
catch (Exception e)
{
e.printStackTrace();
Toast.makeText(this, "Could not initiate File System.. Is Sdcard mounted properly?", Toast.LENGTH_SHORT).show();
return false;
}
}
private boolean makedirs()
{
File tempdir = new File(tempDir);
if (!tempdir.exists())
tempdir.mkdirs();
if (tempdir.isDirectory())
{
File[] files = tempdir.listFiles();
for (File file : files)
{
if (!file.delete())
{
System.out.println("Failed to delete " + file);
}
}
}
return (tempdir.isDirectory());
}
public class signature extends View
{
private static final float STROKE_WIDTH = 5f;
private static final float HALF_STROKE_WIDTH = STROKE_WIDTH / 2;
private Paint paint = new Paint();
private Path path = new Path();
private float lastTouchX;
private float lastTouchY;
private final RectF dirtyRect = new RectF();
public signature(Context context, AttributeSet attrs)
{
super(context, attrs);
paint.setAntiAlias(true);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeWidth(STROKE_WIDTH);
}
public void save(View v)
{
Log.v("log_tag", "Width: " + v.getWidth());
Log.v("log_tag", "Height: " + v.getHeight());
if(mBitmap == null)
{
mBitmap = Bitmap.createBitmap (mContent.getWidth(), mContent.getHeight(), Bitmap.Config.RGB_565);;
}
Canvas canvas = new Canvas(mBitmap);
try
{
FileOutputStream mFileOutStream = new FileOutputStream(mypath);
v.draw(canvas);
mBitmap.compress(Bitmap.CompressFormat.PNG, 90, mFileOutStream);
mFileOutStream.flush();
mFileOutStream.close();
String url = Images.Media.insertImage(getContentResolver(), mBitmap, "title", null);
Log.v("log_tag","url: " + url);
}
catch(Exception e)
{
Log.v("log_tag", e.toString());
}
}
public void clear()
{
path.reset();
invalidate();
}
#Override
protected void onDraw(Canvas canvas)
{
canvas.drawPath(path, paint);
}
#Override
public boolean onTouchEvent(MotionEvent event)
{
float eventX = event.getX();
float eventY = event.getY();
mGetSign.setEnabled(true);
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
path.moveTo(eventX, eventY);
lastTouchX = eventX;
lastTouchY = eventY;
return true;
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
resetDirtyRect(eventX, eventY);
int historySize = event.getHistorySize();
for (int i = 0; i < historySize; i++)
{
float historicalX = event.getHistoricalX(i);
float historicalY = event.getHistoricalY(i);
expandDirtyRect(historicalX, historicalY);
path.lineTo(historicalX, historicalY);
}
path.lineTo(eventX, eventY);
break;
default:
debug("Ignored touch event: " + event.toString());
return false;
}
invalidate((int) (dirtyRect.left - HALF_STROKE_WIDTH),
(int) (dirtyRect.top - HALF_STROKE_WIDTH),
(int) (dirtyRect.right + HALF_STROKE_WIDTH),
(int) (dirtyRect.bottom + HALF_STROKE_WIDTH));
lastTouchX = eventX;
lastTouchY = eventY;
return true;
}
private void debug(String string)
{
}
private void expandDirtyRect(float historicalX, float historicalY)
{
if (historicalX < dirtyRect.left)
{
dirtyRect.left = historicalX;
}
else if (historicalX > dirtyRect.right)
{
dirtyRect.right = historicalX;
}
if (historicalY < dirtyRect.top)
{
dirtyRect.top = historicalY;
}
else if (historicalY > dirtyRect.bottom)
{
dirtyRect.bottom = historicalY;
}
}
private void resetDirtyRect(float eventX, float eventY)
{
dirtyRect.left = Math.min(lastTouchX, eventX);
dirtyRect.right = Math.max(lastTouchX, eventX);
dirtyRect.top = Math.min(lastTouchY, eventY);
dirtyRect.bottom = Math.max(lastTouchY, eventY);
}
}
#Override
public void onLocationChanged(Location mlocation)
{
tvLoc.setText("Latitude: "+ location.getLatitude() +", Longitude: "+ location.getLongitude());
}
#Override
public void onProviderDisabled(String provider)
{
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "GPS Disabled", Toast.LENGTH_SHORT ).show();
}
#Override
public void onProviderEnabled(String provider)
{
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
// TODO Auto-generated method stub
}
}
The code here is a combination of what I got from here, with some modifications. I have commented some stuff out - it may contribute to the error, but at this point, I'm more obsessed with updating the JobStatus object.
And I'm sure that the code above, most notably the UpdateJobTask AsyncTask needs to be fixed heavily.
I haven't had any errors running this, but here is the error log either way:-
05-29 10:33:37.214: W/dalvikvm(17704): threadid=1: thread exiting with uncaught exception (group=0x40f13258)
05-29 10:33:37.226: E/AndroidRuntime(17704): FATAL EXCEPTION: main
05-29 10:33:37.226: E/AndroidRuntime(17704): android.app.SuperNotCalledException: Activity {com.signonglass/com.signonglass.CaptureSignature} did not call through to super.onDestroy()
05-29 10:33:37.226: E/AndroidRuntime(17704): at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3260)
05-29 10:33:37.226: E/AndroidRuntime(17704): at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3289)
05-29 10:33:37.226: E/AndroidRuntime(17704): at android.app.ActivityThread.access$1200(ActivityThread.java:134)
05-29 10:33:37.226: E/AndroidRuntime(17704): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1280)
05-29 10:33:37.226: E/AndroidRuntime(17704): at android.os.Handler.dispatchMessage(Handler.java:99)
05-29 10:33:37.226: E/AndroidRuntime(17704): at android.os.Looper.loop(Looper.java:154)
05-29 10:33:37.226: E/AndroidRuntime(17704): at android.app.ActivityThread.main(ActivityThread.java:4624)
05-29 10:33:37.226: E/AndroidRuntime(17704): at java.lang.reflect.Method.invokeNative(Native Method)
05-29 10:33:37.226: E/AndroidRuntime(17704): at java.lang.reflect.Method.invoke(Method.java:511)
05-29 10:33:37.226: E/AndroidRuntime(17704): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809)
05-29 10:33:37.226: E/AndroidRuntime(17704): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
05-29 10:33:37.226: E/AndroidRuntime(17704): at dalvik.system.NativeStart.main(Native Method)
Thanks in advance for your tips and suggestions guys! :)

To fix the error log, you should call super.onDestroy() in your onDestroy().

Related

Streaming in VideoView without delay via rtsp

Hello I have problem with delay in stream video on android.
I have a delay of about 8 seconds and it is very annoying. There is no delay on the computer.
This is a stream from camera like gopro via wifi --> rtsp.
I found this topic on SO...
Streaming videos on VideoView
And I have the same problem as Akeshwar Jha. Unfortunately, I don't know Java. Could someone help me modify the design according to what Akeshwar Jha gave ??
package com.teststream.robotclient;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.Pair;
import android.widget.VideoView;
import com.jmedeisis.bugstick.Joystick;
import com.jmedeisis.bugstick.JoystickListener;
public class MainActivity extends Activity {
private String host;
private int port;
private DatagramSocket socket;
private VideoView videoView;
private static final String TAG = "MainActivity";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
WifiInfo info = wifiManager.getConnectionInfo();
String ssid = info.getSSID();
String desiredSsid = getString(R.string.ssid);
Log.i(TAG, desiredSsid);
if(!ssid.equals(desiredSsid) && !desiredSsid.equals("*")) {
exitDialog("Wrong SSID", "The SSID of the WIFI network is wrong. Desired SSID: " + desiredSsid);
}
host = getString(R.string.host);
port = Integer.parseInt(getString(R.string.port));
//new CheckConnectivity().execute();
videoView = findViewById(R.id.videoView);
Uri videoUri = Uri.parse(getString(R.string.video_uri));
videoView.setVideoURI(videoUri);
videoView.start();
Joystick left = findViewById(R.id.joystick_left);
Joystick right = findViewById(R.id.joystick_right);
left.setJoystickListener(new JoystickListener() {
#Override
public void onDown() {
log("down");
}
#Override
public void onDrag(float degrees, float offset) {
log("deg: " + degrees + ", off: " + offset);
float upValue = (float) Math.sin(Math.toRadians(degrees)) * offset;
log("" + upValue);
int intValue = normalisedFloatToByte(upValue);
new UpdateServo().execute(Pair.create(0xff, intValue));
}
#Override
public void onUp() {
log("up");
}
});
right.setJoystickListener(new JoystickListener() {
#Override
public void onDown() {
log("down");
}
#Override
public void onDrag(float degrees, float offset) {
log("deg: " + degrees + ", off: " + offset);
float upValue = (float) Math.sin(Math.toRadians(degrees)) * offset;
log("" + upValue);
int intValue = normalisedFloatToByte(upValue);
new UpdateServo().execute(Pair.create(0xfe, intValue));
}
#Override
public void onUp() {
log("up");
}
});
}
private int normalisedFloatToByte(float value) {
if(value < -1.0 || value > 1.0) {
return 0;
}
return 127 + Math.round(value * 127);
}
private void log(String text) {
Log.d(TAG, text);
}
private void exitDialog(String title, String text) {
new AlertDialog.Builder(MainActivity.this)
.setTitle(title)
.setMessage(text)
.setNeutralButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
})
.show();
}
class CheckConnectivity extends AsyncTask<Void, Void, Boolean> {
protected Boolean doInBackground(Void ...params) {
try {
if(!InetAddress.getByName(host).isReachable(2000)) {
return false;
}
} catch (UnknownHostException e) {
return false;
} catch (IOException e) {
return false;
}
return true;
}
protected void onPostExecute(Boolean result) {
if(result == false) {
exitDialog("Can't connect", "Can't connect with host " + host);
}
}
}
class UpdateServo extends AsyncTask<Pair<Integer, Integer>, Void, Void> {
protected Void doInBackground(Pair<Integer, Integer>... requests) {
byte[] payload = {
requests[0].first.byteValue(),
requests[0].second.byteValue()
};
try {
InetAddress addr = InetAddress.getByName(host);
DatagramPacket sendPacket = new DatagramPacket(payload, 0, payload.length, addr, port);
if (socket != null) {
socket.disconnect();
socket.close();
}
socket = new DatagramSocket(port);
socket.send(sendPacket);
} catch (UnknownHostException e) {
Log.e(TAG, "getByName failed");
} catch (IOException e) {
Log.e(TAG, "send failed");
}
return null;
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
Thank you in advance for your help.

How can I use startService() method from a java class

What I am trying to do is that as any incoming call is received I want to start a service ChatHeadService which shows a chat head.
Basically I want to run this command, but as I run the app my app stops at this command.
startService(new Intent(getApplication(), ChatHeadService.class));
This is my java class CallHelper in which I am using thread to use the startService() method.
package com.tarun.notifyme2;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Helper class to detect incoming and outgoing calls.
* #author Moskvichev Andrey V.
*
*/
public class CallHelper extends Activity{
static String incomingNo;
public static final int CONNECTION_TIMEOUT=10000;
public static final int READ_TIMEOUT=15000;
/**
* Listener to detect incoming calls.
*/
private class CallStateListener extends PhoneStateListener {
#Override
public void onCallStateChanged(int state, final String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
// called when someone is ringing to this phone
/*
Intent i; i = getBaseContext().getPackageManager() .getLaunchIntentForPackage
( getBaseContext().getPackageName() ); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);*/
Thread thread = new Thread(){
private int sleepTime = 400;
#Override
public void run() {
super.run();
try {
int wait_Time = 0;
while (wait_Time < sleepTime ) {
sleep(100);
wait_Time += 100;
}
}catch (Exception e) {
Toast.makeText(ctx,
"Error Occured Because:" + e.getMessage(),
Toast.LENGTH_SHORT).show();
}
finally {
}
startService(new Intent(getApplication(), ChatHeadService.class));
//ctx.startActivity(new Intent(ctx, ChatHeadService.class).putExtra("number", incomingNumber)
// .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
//
}
};
thread.run();
incomingNo = incomingNumber;
Toast.makeText(ctx,
"Incoming no is"+incomingNo+" this",
Toast.LENGTH_SHORT).show();
Log.i("check","this no is :"+incomingNo);
/*
SharedPreferences sp = getApplicationContext().getSharedPreferences("Notify", Context.MODE_PRIVATE);
String my_no= sp.getString("my_no","");
*/
String my_no="";
/*
Bundle b = getIntent().getExtras();
if(b!=null){
my_no = b.getString("my_no");
sendNotification(my_no);
}
*/
Log.i("no check",my_no);
//Intent i = new Intent(ctx,SendNoti.class);
//startActivity(i);
break;
}
/*
Log.i("check",incomingNumber);
SharedPreferences sp = getSharedPreferences("phoneno_info",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("incoming",incomingNumber);
editor.commit();*/
}
}
/**
* Broadcast receiver to detect the outgoing calls.
*/
public class OutgoingReceiver extends BroadcastReceiver {
public OutgoingReceiver() {
}
#Override
public void onReceive(Context context, Intent intent) {
String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
/*
Intent i; i = getBaseContext().getPackageManager() .getLaunchIntentForPackage
( getBaseContext().getPackageName() ); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
*/
Toast.makeText(ctx,
"Outgoing: "+number,
Toast.LENGTH_LONG).show();
}
}
private static Context ctx;
private TelephonyManager tm;
private CallStateListener callStateListener;
private OutgoingReceiver outgoingReceiver;
public CallHelper(Context ctx) {
this.incomingNo = incomingNo;
this.ctx = ctx;
callStateListener = new CallStateListener();
outgoingReceiver = new OutgoingReceiver();
/*
SharedPreferences sp = getSharedPreferences("phoneno_info",Context.MODE_PRIVATE);
SharedPreferences.Editor e = sp.edit();
e.putString("incoming",incomingNo);
e.commit();
/*
Intent i = new Intent(ctx,SendNoti.class);
i.putExtra("incoming",incomingNo);*/
// startActivity(i);
}
/**
* Start calls detection.
*/
public void start() {
tm = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
tm.listen(callStateListener, PhoneStateListener.LISTEN_CALL_STATE);
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_NEW_OUTGOING_CALL);
ctx.registerReceiver(outgoingReceiver, intentFilter);
}
/**
* Stop calls detection.
*/
public void stop() {
tm.listen(callStateListener, PhoneStateListener.LISTEN_NONE);
ctx.unregisterReceiver(outgoingReceiver);
}
private void sendNotification(String phone_no){
class SendPostReqAsyncTask extends AsyncTask<String, String, String> {
HttpURLConnection conn;
URL url = null;
#Override
protected String doInBackground(String... params) {
String login_url = "https://notify-me-rajhanssingh.c9users.io/notify_on_incoming.php";
try {
// Enter URL address where your php file resides
url = new URL(login_url);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "Check your internet connection";
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection)url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoInput and setDoOutput method depict handling of both send and receive
conn.setDoInput(true);
conn.setDoOutput(true);
// Append parameters to URL
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("my_no", params[0]);
String query = builder.build().getEncodedQuery();
// Open connection for sending data
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return "Error occured";
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return(result.toString());
}else{
return(" Notification was not sent");
}
} catch (IOException e) {
e.printStackTrace();
return "Error occured";
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result){
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
/*
Intent intent = new Intent(ctx, SendNoti.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ctx.startActivity(intent);*/
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(phone_no);
}
}
My ChatHeadService.class is as follows:
package com.tarun.notifyme2;
import android.app.Service;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
public class ChatHeadService extends Service {
private WindowManager windowManager;
private ImageView chatHead;
WindowManager.LayoutParams params;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
int res = super.onStartCommand(intent, flags, startId);
return res;
}
#Override
public void onCreate() {
super.onCreate();
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
chatHead = new ImageView(this);
chatHead.setImageResource(R.drawable.app_icon);
params= new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP | Gravity.LEFT;
params.x = 0;
params.y = 100;
chatHead.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(ChatHeadService.this,SendNoti.class);
startActivity(i);
stopSelf();
}
});
//this code is for dragging the chat head
chatHead.setOnTouchListener(new View.OnTouchListener() {
private int initialX;
private int initialY;
private float initialTouchX;
private float initialTouchY;
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
initialX = params.x;
initialY = params.y;
initialTouchX = event.getRawX();
initialTouchY = event.getRawY();
return true;
case MotionEvent.ACTION_UP:
return true;
case MotionEvent.ACTION_MOVE:
params.x = initialX
+ (int) (event.getRawX() - initialTouchX);
params.y = initialY
+ (int) (event.getRawY() - initialTouchY);
windowManager.updateViewLayout(chatHead, params);
return true;
}
return false;
}
});
windowManager.addView(chatHead, params);
}
#Override
public void onDestroy() {
super.onDestroy();
if (chatHead != null)
windowManager.removeView(chatHead);
stopSelf();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
This is the error message I am getting
08-12 00:49:51.858 22016-22016/com.tarun.notifyme2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.tarun.notifyme2, PID: 22016
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.content.ComponentName.<init>(ComponentName.java:77)
at android.content.Intent.<init>(Intent.java:4286)
at com.tarun.notifyme2.CallHelper$CallStateListener$1.run(CallHelper.java:73)
at com.tarun.notifyme2.CallHelper$CallStateListener.onCallStateChanged(CallHelper.java:82)
at android.telephony.PhoneStateListener$1.handleMessage(PhoneStateListener.java:293)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5292)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)

Android view alert msg when i receive messege from service

Hi i have a problem on my project, i have one activity and service , i use messenger to communication with us. I would view a alert dialog when i receive a message from service ,but this dialog is not appear. On log cat i see a log with text.
Do you have a solution .
My code is:
import java.lang.ref.WeakReference;
import java.util.List;
import java.util.Map;
import ztl.Bologna.activity.Database.DBopenHelper;
import ztl.Bologna.OverlayList;
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.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Messenger;
import android.provider.BaseColumns;
import android.app.AlertDialog;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.Menu;
public class MapsActivity extends MapActivity{
private MyLocationOverlay mOverlay;
protected static MapView gmap;
private DBopenHelper db;
OverlayList overlay;
private GuiHandler guiHandler;
private Messenger messenger;
public double destLat = 44.497592;
public double destLong = 11.356151;
private double Long = 11.352693;
private double Lat = 44.497271;
Intent serviceIntent;
public Cursor cursor;
int version ;
//final MapController control = gmap.getController();
GeoPoint gp = new GeoPoint((int)(Lat * 1e6),(int)(Long * 1e6));
//Context c = getApplicationContext();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
Context context;
context = getApplicationContext();
Log.e("context",""+context);
//db = new DBopenHelper(context);
db = new DBopenHelper(this,1);
guiHandler = new GuiHandler(this);
Log.d("put", "database");
gmap=(MapView)findViewById(R.id.mapview);
gmap.setClickable(true);
gmap.setBuiltInZoomControls(true);
mOverlay=new MyLocationOverlay(this,gmap);
//control.setCenter(gp);
// control.animateTo(gp);
gmap.getOverlays().add(mOverlay);
Lat=44.497271;
Long=11.352693;
updateMapOverlay();
db.close();
messenger = new Messenger(guiHandler);
serviceIntent = new Intent(MapsActivity.this,MessaggeService.class);
serviceIntent.putExtra(MessaggeService.CALLER, MessaggeService.POSITION);
serviceIntent.putExtra(MessaggeService.MESSENGER, messenger);
startService(serviceIntent);
Log.e("Debug", "Service Started from activity");
//ms = new MessaggeService(overlay,gmap,c);
///destLat = mOverlay.getMyLocation().getLatitudeE6();
//destLong = mOverlay.getMyLocation().getLongitudeE6();
}
private void addOpenPoint(GeoPoint g) {
OverlayItem overlayitem = new OverlayItem(g, "", "");
overlay.addOverlay(overlayitem);
Log.e("over",""+overlayitem);
}
protected void onResume() {
super.onResume();
mOverlay.enableMyLocation();
mOverlay.runOnFirstFix(new Runnable() {
// #Override
public void run() {
//gmap.invalidate();
gmap.getController().animateTo(mOverlay.getMyLocation());
gmap.getController().setZoom(16);
//updateMapOverlay();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_maps, menu);
return true;
}
void updateMapOverlay() {
List<Overlay> mapOverlays = gmap.getOverlays();
Drawable drawable = getResources().getDrawable(R.drawable.ic_launcher);
//mapOverlays.clear();
overlay = new OverlayList(drawable, this);
mapOverlays.add(overlay);
Cursor cursor = db.getZtlStreet();
if (cursor.moveToFirst()) {
while(cursor.moveToNext()) {
Integer lat = (int) (cursor.getDouble(cursor.getColumnIndex("latitude")) * 1e6);
Integer lon = (int) (cursor.getDouble(cursor.getColumnIndex("longitude")) * 1e6);
GeoPoint p = new GeoPoint(lat, lon);
addOpenPoint(p);
}
}
}
public static class GuiHandler extends Handler {
// TODO da unificare con quello ChooseEVSEActivity
public static final int FALSE = 0;
public static final int TRUE = 1;
// tiene il conto del tempo che è passato dall'ultima volta;
WeakReference<MapsActivity> wrActivity;
public GuiHandler(MapsActivity activity) {
wrActivity = new WeakReference<MapsActivity>(activity);
}
public void handleMessage(android.os.Message msg) {
final MapsActivity activity = wrActivity.get();
/*Create alert dialog to access on ztl street*/
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setMessage("Accesso Ztl non puoi accedere");
builder.setPositiveButton("chiudi",new DialogInterface.OnClickListener() {
//#Override
public void onClick(DialogInterface dialog, int id) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
switch (msg.what) {
case MessaggeService.UPDATE_UI_MSG:
AlertDialog alertMsg = builder.create();
alertMsg.show();
break;
}
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
My service with message is :
for(int i = 0 ; i< overlay.size();i++){
Log.e("item : ","n"+overlay.size());
OverlayItem item = overlay.getItem(i);
Location l1 = new Location("");
l1.setLatitude(item.getPoint().getLatitudeE6());
Log.e("l1", "l1"+l1.getLatitude());
l1.setLongitude(item.getPoint().getLongitudeE6());
Location l2 = new Location("");
l2.setLatitude(destLat);
l2.setLongitude(destLong);
Log.e("l2", "l2"+l2.getLatitude());
try {
String caller = "generic";
try {
caller = intent.getStringExtra(CALLER);
Bundle extras = intent.getExtras();
if (extras != null) {
if (POSITION.equals(caller)) {
positionMessenger = (Messenger) extras.get(MESSENGER);
Log.e("position",""+positionMessenger);
}
}
System.out.println("Instantiating " + caller + " Messenger OK :" + positionMessenger);
} catch (Exception e) {
//Log.e(UpdaterService.class.getName(), "Error instantiating " + caller + " Messenger" + e.getMessage());
//se il servizio non è ancora partito allora esco da esso in modo che venga istanziato correttamente
if(!doUpdate) {
stopSelf();
}
}
if (l2.distanceTo(l1) >100) {
Log.e("distance","Ztl non puoi accedere");
Message msg = Message.obtain();
Log.e("msg",""+msg);
msg.what = UPDATE_UI_MSG;
positionMessenger.send(msg);
Log.e("send","send");
}} catch (RemoteException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
You need to order the builder to show at the end
builder.show();

custom listview scrolling is stuttering

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

Plotting points on a MapView after Panning and Zooming

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());
}
}
}
}

Categories

Resources