BroadCast Receiver makes slowly works to other services - android

when I listen push message from BroadcastReceiver I can take message but it makes slow other services for example I am sending "Message is taken" to my web service when I take push message but I can't send to my webservice it works very slowly when I listen to BroadcastReceiver for take message and when I delete BroadcastReceiver I can send message to my webservice very fastly
package jsonparse;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.androidhive.pushnotifications.MapsActivity;
import com.androidhive.pushnotifications.R;
import com.androidhive.pushnotifications.ServerUtilities;
import com.androidhive.pushnotifications.WakeLocker;
import com.daasuu.ahp.AnimateHorizontalProgressBar;
import com.google.android.gcm.GCMRegistrar;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static com.androidhive.pushnotifications.CommonUtilities.DISPLAY_MESSAGE_ACTION;
import static com.androidhive.pushnotifications.CommonUtilities.EXTRA_MESSAGE;
import static com.androidhive.pushnotifications.CommonUtilities.SENDER_ID;
public class ListViewAdapter extends BaseAdapter implements OnClickListener{
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
//ProgressBar mprogressBar;
TextView fulness;
TextView location_info;
TextView descrip;
JSONObject jsonobject;
private Handler mHandler = new Handler();
private int mProgressStatus=0;
String get_enlem,get_boylam;
double dble_get_enlem,dble_get_boylam;
String dest_city_name,dest_state_name,dest_country_name;
NetworkInfo ni;
ConnectivityManager cm;
String get_location;
String device_id;
String sonuc;
SharedPreferences prefs;
String get_groupID, get_customerID;
String get_desc;
String get_toplam;
// Asyntask
AsyncTask<Void, Void, Void> mRegisterTask;
public static String name;
public static String email;
Context con;
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
/*
TextView rank;
TextView country;
TextView population;
ImageView flag;
*/
TextView location;
AnimateHorizontalProgressBar progressBar;
Button cop_toplandi;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.listview_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
//rank = (TextView) itemView.findViewById(R.id.rank);
//country = (TextView) itemView.findViewById(R.id.country);
//population = (TextView) itemView.findViewById(R.id.population);
//Get Device IMEI number
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
device_id = telephonyManager.getDeviceId();
Log.i("IMEI NUMBER", device_id);
// Getting name, email from intent
Intent i = ((Activity) context).getIntent();
name = i.getStringExtra("get_message_name");
email = i.getStringExtra("email");
Handler handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(context);
// Make sure the manifest was properly set - comment out this line
// while developing the app, then uncomment it when it's ready.
GCMRegistrar.checkManifest(context);
context.registerReceiver(mHandleMessageReceiver, new IntentFilter(
DISPLAY_MESSAGE_ACTION));
// Get GCM registration id
final String regId = GCMRegistrar.getRegistrationId(context);
// Check if regid already presents
if (regId.equals("")) {
// Registration is not present, register now with GCM
GCMRegistrar.register(context, SENDER_ID);
} else {
// Device is already registered on GCM
if (GCMRegistrar.isRegisteredOnServer(context)) {
// Skips registration.
// Toast.makeText(getApplicationContext(), "Already registered with GCM", Toast.LENGTH_LONG).show();
} else {
// 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 contextm = context;
mRegisterTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
// Register on our server
// On server creates a new user
ServerUtilities.register(contextm, name, email, regId);
return null;
}
#Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}
};
mRegisterTask.execute(null, null, null);
}
}
}
};
handler.postDelayed(r, 1000);
prefs = context.getSharedPreferences("login_page", context.MODE_PRIVATE);
get_groupID = prefs.getString("user_groupID", "alınmadı");
get_customerID = prefs.getString("user_customerID", "alınmadı");
if (get_groupID.equals("null")) {
get_groupID = "0";
}
if (get_customerID.equals("null")) {
get_customerID = "0";
}
location = (TextView) itemView.findViewById(R.id.location);
progressBar = (AnimateHorizontalProgressBar) itemView.findViewById(R.id.animate_progress_bar);
fulness = (TextView) itemView.findViewById(R.id.txt_percentage_of_fulness);
descrip = (TextView) itemView.findViewById(R.id.txt_desc);
get_location = resultp.get(MainActivity.COUNTRY);
cop_toplandi = (Button) itemView.findViewById(R.id.secret_button);
cop_toplandi.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context.getApplicationContext(),"Başarıyla Gönderildi",Toast.LENGTH_SHORT).show();
new Send_save_status().execute();
}
});
location_info = (TextView) itemView.findViewById(R.id.location_info);
// Locate the ImageView in listview_item.xml
//flag = (ImageView) itemView.findViewById(R.id.flag);
// Capture position and set results to the TextViews
//rank.setText(resultp.get(MainActivity.RANK));
//country.setText(resultp.get(MainActivity.COUNTRY));
//population.setText(resultp.get(MainActivity.POPULATION));
location.setText(resultp.get(MainActivity.COUNTRY));
location_info.setText(resultp.get(MainActivity.Location_info));
String get_descrip = resultp.get(MainActivity.DESCB);
if(get_descrip != "0"){
descrip.setText(resultp.get(MainActivity.DESCB));
cop_toplandi.setVisibility(View.VISIBLE);
}
get_enlem = resultp.get(MainActivity.POPULATION);
get_boylam = resultp.get(MainActivity.FLAG);
get_toplam = resultp.get(MainActivity.Toplam);
//dble_get_enlem = Double.parseDouble(get_enlem);
//dble_get_boylam = Double.parseDouble(get_boylam);
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
//imageLoader.DisplayImage(resultp.get(MainActivity.FLAG), flag);
// Capture ListView item click
String a = resultp.get(MainActivity.RANK);
int b = Integer.parseInt(a);
progressBar.setMax(100);
progressBar.setProgress(b);
//progressBar.setProgressWithAnim(b);
fulness.setText("%"+(b*1));
//mprogressBar = (ProgressBar) itemView.findViewById(R.id.progressBar);
//mprogressBar.setProgress(b);
/*
ObjectAnimator anim = ObjectAnimator.ofInt(mprogressBar, "progress", 0, 80);
anim.setDuration(5000);
anim.setInterpolator(new DecelerateInterpolator());
anim.start();
*/
/*
//Get location name from latitude and longitude
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(dble_get_enlem, dble_get_boylam, 1);
} catch (IOException e) {
e.printStackTrace();
}
dest_city_name = addresses.get(0).getAddressLine(0);
dest_state_name = addresses.get(0).getAddressLine(1);
dest_country_name = addresses.get(0).getAddressLine(2);
location_info.setText(dest_city_name + " " + dest_country_name);
*/
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
ni = cm.getActiveNetworkInfo();
if (ni != null && ni.isConnected()) {
Toast.makeText(context,context.getString(R.string.progressdialog_message), Toast.LENGTH_SHORT).show();
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, MapsActivity.class);
// Pass all data rank
intent.putExtra("level", resultp.get(MainActivity.RANK));
// Pass all data country
intent.putExtra("imei", resultp.get(MainActivity.COUNTRY));
// Pass all data population
intent.putExtra("enlem",resultp.get(MainActivity.POPULATION));
// Pass all data flag
intent.putExtra("boylam", resultp.get(MainActivity.FLAG));
// Start SingleItemView Class
context.startActivity(intent);
}else{
Toast.makeText(context.getApplicationContext(),context.getApplicationContext().getString(R.string.network_connection),Toast.LENGTH_SHORT).show();
}
}
});
return itemView;
}
#Override
public void onClick(View v) {
switch (v.getId()){
}
}
/**
* Receiving push messages
* */
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
// Waking up mobile if it is sleeping
WakeLocker.acquire(context);
//context.sendBroadcast(new Intent("com.google.android.intent.action.GTALK_HEARTBEAT"));
//context.sendBroadcast(new Intent("com.google.android.intent.action.MCS_HEARTBEAT"));
// Showing received message
//lblMessage.append(newMessage + "\n");
//Toast.makeText(getApplicationContext(), "New Message: " + newMessage, Toast.LENGTH_LONG).show();
//descrip.setText(newMessage);
// Intent go = new Intent(context.getApplicationContext(),IsEmri.class);
//context.startActivity(go);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Acil Durum!!!");
builder.setMessage(newMessage)
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// TODO: handle the OK
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
// Releasing wake lock
WakeLocker.release();
}
};
/*
Send GroupID and customerID every five minutes to services
*/
private class Send_save_status extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
}
#Override
protected Void doInBackground(Void... params) {
//Toast.makeText(getApplicationContext(), getApplicationContext().getString(R.string.gprs_adres) + address, Toast.LENGTH_LONG).show();
// make sure you close the gps after using it. Save user's battery power
//mGPSService.closeGPS();
StringBuilder str_url = new StringBuilder();
str_url.append("http://78.186.62.169:8090/TrackBinSvc.svc/saveStatus/");
Log.i("str_url1", "" + str_url);
str_url.append(device_id + "/");
Log.i("strl_url2", "" + str_url);
str_url.append(get_location + "/");
Log.i("strl_url3", "" + str_url);
str_url.append("opened" + "/");
Log.i("strl_url3", "" + str_url);
str_url.append(get_groupID + "/");
Log.i("strl_url3", "" + str_url);
str_url.append(get_customerID);
Log.i("strl_url3", "" + str_url);
String str = str_url.toString();
//"http://192.168.0.39:8090/TrackBinSvc.svc/Get_All_Mobile/admin/1234"
try {
jsonobject = JSONfunctions
.getJSONfromURL(str);
// Locate the array name in JSON
sonuc = jsonobject.getString("SendUpdateCordinatesResult");
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
}
}
}

Problem is: The broadcast receiver that you are registering is implemented on the Main thread. The broadcast receiver handler is ALWAYS EXECUTED ON THE MAIN THREAD, thus, making your entire process slower. To implement receiver's own thread, you can explicitly do so by providing it's own Handler thread.
Register your broadcast receiver like this:
HandlerThread receiverHandlerThread = new HandlerThread("threadName");
receiverHandlerThread.start();
Looper looper = receiverHandlerThread.getLooper();
Handler handler = new Handler(looper);
context.registerReceiver(mHandleMessageReceiver,newIntentFilter(DISPLAY_MESSAGE_ACTION),null,handler);

Related

unable to get the notification when the messsage arrives from gcm android

Example: In my application I have client,distributors and server.client ask questions to server and server will reply for that question via Gcm push notification.I have implemented this by googling it and push notification tutorials.
And my issue is, if I send a question from client,it gets displayed in server by parsing the link but I'm not getting the push notification. any one help me with this.I don't know where I have done mistake. Any suggestion to implement this functionality via push notification. server side script is write in php
I have posted the server part code...here only i want the push notification
my GCM class
import java.util.Timer;
import java.util.TimerTask;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.RingtoneManager;
import android.os.PowerManager;
import android.util.Log;
import android.widget.Toast;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import com.google.android.gcm.GCMBaseIntentService;
public class GCMIntentService extends GCMBaseIntentService
{
private static final String TAG = "GCM Tutorial::Service";
// Use your PROJECT ID from Google API into SENDER_ID
public static final String SENDER_ID = "projectid";
//SharedPreferences prefs;
//DbHelper db;
String xx = "";
public GCMIntentService() {
super(SENDER_ID);
}
#Override
protected void onRegistered(Context context, String registrationId) {
//prefs = this.getSharedPreferences("", Context.MODE_PRIVATE);
//SharedPreferences.Editor prefsEditor = prefs.edit();
//prefsEditor.putString("registrationid", registrationId);
//prefsEditor.commit();
Log.i(TAG, "onRegistered: registrationId=" + registrationId);
xx = registrationId;
Toast.makeText(getApplicationContext(), xx, Toast.LENGTH_LONG).show();
System.out.println("Register : "+registrationId);
}
#Override
protected void onUnregistered(Context context, String registrationId) {
Log.i(TAG, "onUnregistered: registrationId=" + registrationId);
}
#SuppressLint("NewApi")
#Override
protected void onMessage(Context context, Intent data) {
//db = new DbHelper(context);
//db.openToWrite();
String message;
// Message from PHP server
message = data.getStringExtra("message");
// Open a new activity called GCMMessageView
//db.insertmessage(message);
System.out.println("inside gcm class");
Intent intent = new Intent(this, MainActivity.class);
// Pass data to the new activity
intent.putExtra("message", message);
// Starts the activity on notification click
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
// Create the notification with a notification builder
Notification notification = new Notification.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setWhen(System.currentTimeMillis())
.setContentTitle("New message")
.setContentText(message).setContentIntent(pIntent)
.getNotification();
// Remove the notification on click
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.sound =
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notification.defaults |= Notification.DEFAULT_VIBRATE;
NotificationManager manager = (NotificationManager)context.getSystemService(NOTIFICATION_SERVICE);
manager.notify(R.string.app_name, notification);
{
// Wake Android Device when notification received
PowerManager pm = (PowerManager) context
.getSystemService(Context.POWER_SERVICE);
final PowerManager.WakeLock mWakelock = pm.newWakeLock(
PowerManager.FULL_WAKE_LOCK
| PowerManager.ACQUIRE_CAUSES_WAKEUP, "GCM_PUSH");
mWakelock.acquire();
// Timer before putting Android Device to sleep mode.
Timer timer = new Timer();
TimerTask task = new TimerTask() {
public void run() {
mWakelock.release();
}
};
timer.schedule(task, 5000);
}
}
#Override
protected void onError(Context arg0, String errorId) {
Log.e(TAG, "onError: errorId=" + errorId);
}
}
question class
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class prompt extends Activity
{
Button prompt_ok,prompt_cancel;
private static final String url="http://maps.googleapis.com/maps/api/geocode/json?address=";
private static final String url1="&sensor=false";
EditText zip,noofsup;
JSONArray results;
JSONObject geometry,location;
String latt,lngg,ques;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent in=getIntent();
ques=in.getStringExtra("questionfornext");
setContentView(R.layout.prompt);
zip=(EditText)findViewById(R.id.zipcode);
noofsup=(EditText)findViewById(R.id.noofsupplier);
}
public void onClick(View view)
{
String zipcode=zip.getText().toString();
String finalurl=url+zipcode+url1;
new GetData().execute();
new GetRegister().execute();
new GetQuestion().execute();
Intent in=new Intent(getApplicationContext(),MainActivity.class);
startActivity(in);
setContentView(R.layout.activity_main);
}
public void onCancel(View v)
{
Intent in=new Intent(getApplicationContext(),MainActivity.class);
startActivity(in);
setContentView(R.layout.activity_main);
}
private class GetData extends AsyncTask<Void, Void, Void>
{
String status;
String zipcode=zip.getText().toString();
String finalurl=url+zipcode+url1;
#Override
protected void onPreExecute()
{
super.onPreExecute();
// Showing progress dialog
}
#Override
protected Void doInBackground(Void... arg0)
{
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(finalurl, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null)
{
try
{
JSONObject jsonObj = new JSONObject(jsonStr);
status=jsonObj.getString("status");
System.out.println("status"+status);
results=jsonObj.getJSONArray("results");
for(int j=0;j==0;j++)
{
JSONObject c=results.getJSONObject(0);
geometry=c.getJSONObject("geometry");
JSONObject ob=geometry.getJSONObject("location");
latt=ob.getString("lat");
lngg=ob.getString("lng");
// String latt=location.getString("lat");
//String lngg=location.getString("lng");
System.out.println("latt"+latt);
System.out.println("lng"+lngg);
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
else
{
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
if(status.equals("OK"))
{
new GetRegister().execute();
//Toast.makeText(getApplicationContext(), msg1, Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "Enter Valid ZIP", Toast.LENGTH_LONG).show();
}
}
}
private class GetRegister extends AsyncTask<Void, Void, Void>
{
//String android_id = Secure.getString(getContentResolver(),Secure.ANDROID_ID);
String weburl="register url ";//if we ask question it will automatically register
String weburl1="&latitude=";
String weburl2="&longtitude=";
String weburl3="&type=Android&author=Jers&Submit=submit";
String code,msg;
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
ServiceHandler sh=new ServiceHandler();
String finalweburl=weburl+MainActivity.androidId+weburl1+latt+weburl2+lngg+weburl3;
System.out.println("new final web url----////"+finalweburl);
String str=sh.makeServiceCall(finalweburl,ServiceHandler.GET);
if(str!=null)
{
try
{
JSONObject obj=new JSONObject(str);
code=obj.getString("code");
msg=obj.getString("msg");
System.out.println("jewellery id-----"+MainActivity.androidId);
System.out.println("code-----"+code);
}
catch(JSONException e)
{
e.printStackTrace();
}
}
else
{
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
if(code.equals("1"))
{
new GetQuestion().execute();
Toast.makeText(getApplicationContext(), "Registered", Toast.LENGTH_SHORT).show();
}
else
{
// Toast.makeText(getApplicationContext(),"NOT a question", Toast.LENGTH_LONG).show();
}
}
}
private class GetQuestion extends AsyncTask<Void, Void, Void>
{
EditText question1=(EditText)findViewById(R.id.question);
String success,msg1;
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
String noofsupplier=noofsup.getText().toString();
ServiceHandler sh=new ServiceHandler();
String android_id = Secure.getString(getContentResolver(),Secure.ANDROID_ID);
String url="request url for distributor ";
String url1="&question=";
String url2="&no_of_suppliers=";
String finalurlq1=url+android_id+url1+ques+url2+noofsupplier;
String finalurlq=new String(finalurlq1.replaceAll(" ","%20"));
System.out.println(finalurlq);
System.out.println("question---->"+ques);
String str1=sh.makeServiceCall(finalurlq,ServiceHandler.GET);
if(str1!=null)
{
try
{
JSONObject ob=new JSONObject(str1);
JSONObject ob1=ob.getJSONObject("response");
success=ob1.getString("success");
msg1=ob1.getString("msg");
System.out.println("success---->"+success);
System.out.println("msg----->"+msg1);
}
catch(JSONException e)
{
e.printStackTrace();
}
}
else
{
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
// Dismiss the progress dialog
// if (pDialog.isShowing())
// pDialog.dismiss();
/* * Updating parsed JSON data into ListView**/
if(success.equals("1"))
{
Toast.makeText(getApplicationContext(), "Question is Registered", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "Question not registered", Toast.LENGTH_SHORT).show();
}
}
}
}

USB Serial communication between Android and computer

I need to create an App that receives and transmit text data from a computer to a Android App. I found this : https://github.com/mik3y/usb-serial-for-android.
I used the example to see if I starting like this I could see a comunication between then, when I used in my mobile it appears 1 device found Vendor 1519 Product 0020 No Driver. It's like not happened the communication and not found the computer.
Here is the code:
SerialConsoleActivity.java--
package com.hoho.android.usbserial.examples;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.ScrollView;
import android.widget.TextView;
import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.util.HexDump;
import com.hoho.android.usbserial.util.SerialInputOutputManager;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Monitors a single {#link UsbSerialDriver} instance, showing all data
* received.
*
* #author mike wakerly (opensource#hoho.com)
*/
public class SerialConsoleActivity extends Activity {
private final String TAG = SerialConsoleActivity.class.getSimpleName();
/**
* Driver instance, passed in statically via
* {#link #show(Context, UsbSerialDriver)}.
*
* <p/>
* This is a devious hack; it'd be cleaner to re-create the driver using
* arguments passed in with the {#link #startActivity(Intent)} intent. We
* can get away with it because both activities will run in the same
* process, and this is a simple demo.
*/
private static UsbSerialDriver sDriver = null;
private TextView mTitleTextView;
private TextView mDumpTextView;
private ScrollView mScrollView;
private final ExecutorService mExecutor = Executors.newSingleThreadExecutor();
private SerialInputOutputManager mSerialIoManager;
private final SerialInputOutputManager.Listener mListener =
new SerialInputOutputManager.Listener() {
#Override
public void onRunError(Exception e) {
Log.d(TAG, "Runner stopped.");
}
#Override
public void onNewData(final byte[] data) {
SerialConsoleActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
SerialConsoleActivity.this.updateReceivedData(data);
}
});
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.serial_console);
mTitleTextView = (TextView) findViewById(R.id.demoTitle);
mDumpTextView = (TextView) findViewById(R.id.consoleText);
mScrollView = (ScrollView) findViewById(R.id.demoScroller);
}
#Override
protected void onPause() {
super.onPause();
stopIoManager();
if (sDriver != null) {
try {
sDriver.close();
} catch (IOException e) {
// Ignore.
}
sDriver = null;
}
finish();
}
#Override
protected void onResume() {
super.onResume();
Log.d(TAG, "Resumed, sDriver=" + sDriver);
if (sDriver == null) {
mTitleTextView.setText("No serial device.");
} else {
try {
sDriver.open();
sDriver.setParameters(115200, 8, UsbSerialDriver.STOPBITS_1, UsbSerialDriver.PARITY_NONE);
} catch (IOException e) {
Log.e(TAG, "Error setting up device: " + e.getMessage(), e);
mTitleTextView.setText("Error opening device: " + e.getMessage());
try {
sDriver.close();
} catch (IOException e2) {
// Ignore.
}
sDriver = null;
return;
}
mTitleTextView.setText("Serial device: " + sDriver.getClass().getSimpleName());
}
onDeviceStateChange();
}
private void stopIoManager() {
if (mSerialIoManager != null) {
Log.i(TAG, "Stopping io manager ..");
mSerialIoManager.stop();
mSerialIoManager = null;
}
}
private void startIoManager() {
if (sDriver != null) {
Log.i(TAG, "Starting io manager ..");
mSerialIoManager = new SerialInputOutputManager(sDriver, mListener);
mExecutor.submit(mSerialIoManager);
}
}
private void onDeviceStateChange() {
stopIoManager();
startIoManager();
}
private void updateReceivedData(byte[] data) {
final String message = "Read " + data.length + " bytes: \n"
+ HexDump.dumpHexString(data) + "\n\n";
mDumpTextView.append(message);
mScrollView.smoothScrollTo(0, mDumpTextView.getBottom());
}
/**
* Starts the activity, using the supplied driver instance.
*
* #param context
* #param driver
*/
static void show(Context context, UsbSerialDriver driver) {
sDriver = driver;
final Intent intent = new Intent(context, SerialConsoleActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY);
context.startActivity(intent);
}
}
DeviceListActivity--
import android.app.Activity;
import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.TwoLineListItem;
import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialProber;
import com.hoho.android.usbserial.util.HexDump;
import java.util.ArrayList;
import java.util.List;
/**
* Shows a {#link ListView} of available USB devices.
*
* #author mike wakerly (opensource#hoho.com)
*/
public class DeviceListActivity extends Activity {
private final String TAG = DeviceListActivity.class.getSimpleName();
private UsbManager mUsbManager;
private ListView mListView;
private TextView mProgressBarTitle;
private ProgressBar mProgressBar;
private static final int MESSAGE_REFRESH = 101;
private static final long REFRESH_TIMEOUT_MILLIS = 5000;
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_REFRESH:
refreshDeviceList();
mHandler.sendEmptyMessageDelayed(MESSAGE_REFRESH, REFRESH_TIMEOUT_MILLIS);
break;
default:
super.handleMessage(msg);
break;
}
}
};
/** Simple container for a UsbDevice and its driver. */
private static class DeviceEntry {
public UsbDevice device;
public UsbSerialDriver driver;
DeviceEntry(UsbDevice device, UsbSerialDriver driver) {
this.device = device;
this.driver = driver;
}
}
private List<DeviceEntry> mEntries = new ArrayList<DeviceEntry>();
private ArrayAdapter<DeviceEntry> mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
mListView = (ListView) findViewById(R.id.deviceList);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
mProgressBarTitle = (TextView) findViewById(R.id.progressBarTitle);
mAdapter = new ArrayAdapter<DeviceEntry>(this, android.R.layout.simple_expandable_list_item_2, mEntries) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final TwoLineListItem row;
if (convertView == null){
final LayoutInflater inflater =
(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = (TwoLineListItem) inflater.inflate(android.R.layout.simple_list_item_2, null);
} else {
row = (TwoLineListItem) convertView;
}
final DeviceEntry entry = mEntries.get(position);
final String title = String.format("Vendor %s Product %s",
HexDump.toHexString((short) entry.device.getVendorId()),
HexDump.toHexString((short) entry.device.getProductId()));
row.getText1().setText(title);
final String subtitle = entry.driver != null ?
entry.driver.getClass().getSimpleName() : "No Driver";
row.getText2().setText(subtitle);
return row;
}
};
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(new ListView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "Pressed item " + position);
if (position >= mEntries.size()) {
Log.w(TAG, "Illegal position.");
return;
}
final DeviceEntry entry = mEntries.get(position);
final UsbSerialDriver driver = entry.driver;
if (driver == null) {
Log.d(TAG, "No driver.");
return;
}
showConsoleActivity(driver);
}
});
}
#Override
protected void onResume() {
super.onResume();
mHandler.sendEmptyMessage(MESSAGE_REFRESH);
}
#Override
protected void onPause() {
super.onPause();
mHandler.removeMessages(MESSAGE_REFRESH);
}
private void refreshDeviceList() {
showProgressBar();
new AsyncTask<Void, Void, List<DeviceEntry>>() {
#Override
protected List<DeviceEntry> doInBackground(Void... params) {
Log.d(TAG, "Refreshing device list ...");
SystemClock.sleep(1000);
final List<DeviceEntry> result = new ArrayList<DeviceEntry>();
for (final UsbDevice device : mUsbManager.getDeviceList().values()) {
final List<UsbSerialDriver> drivers =
UsbSerialProber.probeSingleDevice(mUsbManager, device);
Log.d(TAG, "Found usb device: " + device);
if (drivers.isEmpty()) {
Log.d(TAG, " - No UsbSerialDriver available.");
result.add(new DeviceEntry(device, null));
} else {
for (UsbSerialDriver driver : drivers) {
Log.d(TAG, " + " + driver);
result.add(new DeviceEntry(device, driver));
}
}
}
return result;
}
#Override
protected void onPostExecute(List<DeviceEntry> result) {
mEntries.clear();
mEntries.addAll(result);
mAdapter.notifyDataSetChanged();
mProgressBarTitle.setText(
String.format("%s device(s) found",Integer.valueOf(mEntries.size())));
hideProgressBar();
Log.d(TAG, "Done refreshing, " + mEntries.size() + " entries found.");
}
}.execute((Void) null);
}
private void showProgressBar() {
mProgressBar.setVisibility(View.VISIBLE);
mProgressBarTitle.setText(R.string.refreshing);
}
private void hideProgressBar() {
mProgressBar.setVisibility(View.INVISIBLE);
}
private void showConsoleActivity(UsbSerialDriver driver) {
SerialConsoleActivity.show(this, driver);
}
}
Have you installed the driver your phone migh require to work? For example any Samsung smartphone will require the Key-software to be installed in order for the drivers to function properly. I am asuming you want to try USB-debugging, correct?
It seems that you don't have the right driver installed for your device.Try firstly to use google official tools for android development like adb and friends. If they don't work than you don't have the driver. Visit the site of the vendor of your mobile phone and download it.
It seems that you lack of USB driver.The driver should be download at http://www.ftdichip.com/Drivers/VCP.htm
according to you system version. The same problem confused me, and that driver solves this problem. Hope it works for you.

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

create thread from other thread throw exception like Can't create handler inside thread that has not called Looper.prepare()

hi i am new in android and i need to start 2 webservices on click of button.
first need to call one service and depend on response of that service
need to start second service using thread because i need to call 2nd service periodically.
below is my on click code
import java.io.IOException;
import org.apache.http.client.ClientProtocolException;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class startWork extends Activity implements LocationListener {
private LocationManager locationManager;
private MyProgressDialog progressDialog;
private String provider;
private static ProgressDialog progDailog;
public static String latitude = "0";
public static String longitude = "0";
public static String userid = "";
public static String password = "";
public static String activationid = "";
public static long locationSendingPeriod = 1000;
public static String role = "Driver";
public static int j = 0;
public static int i = 0;
static final String ACTION = "com.google.android.c2dm.intent.RECEIVE";
private Handler mHandler = new Handler();
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
long millis = SystemClock.uptimeMillis();
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
// put your code below to run every second
try {
// latitude = "31.794483";
// longitude = "34.641747";
String DriverUpdateXml = soapXml.getDriverUpdateLocation(
startWork.userid, startWork.password,
startWork.activationid, startWork.role, latitude,
longitude);
Soap.getSoapResponse(DriverUpdateXml);
} catch (Exception e) {
// TODO Auto-generated catch block
}
// end put your code below to run every second
mHandler.postAtTime(this, startWork.locationSendingPeriod
+ (((minutes * 60) + seconds + 1) * 1000));
}
};
**// this is my method which is call onclick of button**
public void changeWorkStatus(View view) throws ClientProtocolException,
IOException {
progressDialog = new MyProgressDialog(this);
new Thread(new Runnable() {
public void run() {
try {
// progressHandler.postDelayed(progressUpdate, 100);
// progDailog = ProgressDialog.show(this, "", "");
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(startWork.this);
Button btnWork = (Button) findViewById(R.id.buttonStartWork);
String workText = btnWork.getText().toString();
String start_work = getResources().getString(
R.string.start_work);
String finish_work = getResources().getString(
R.string.finish_work);
String userid = prefs.getString(CreateDriver.PREFS_UserId,
"");
String password = prefs.getString(
CreateDriver.PREFS_Password, "");
String activationid = prefs.getString(
CreateDriver.PREFS_ActivationId, "");
String role = "Driver";
if (workText.equals(start_work)) {
// LocationManager mlocManager = (LocationManager)
// getSystemService(Context.LOCATION_SERVICE);
// LocationListener mlocListener = new
// taxiLocationListener();
// mlocManager.requestLocationUpdates(
// LocationManager.GPS_PROVIDER, 1000, (float) 0.01,
// mlocListener);
// String latitude = "31.794483";
// String longitude = "34.641747";
String DriverChangeStatus = soapXml.getDriverLogIn(
userid, password, activationid, role,
latitude.toString(), longitude.toString());
String resp = Soap.getSoapResponse(DriverChangeStatus);
org.w3c.dom.Document doc = XMLfunctions
.XMLfromString(resp);
NodeList nodes = doc.getElementsByTagName("Status");
Element elem = (Element) nodes.item(0);
String opt = XMLfunctions.getValue(elem, "Status");
nodes = doc
.getElementsByTagName("LocationSendingPeriod");
elem = (Element) nodes.item(0);
locationSendingPeriod = Long.valueOf(XMLfunctions
.getValue(elem, "LocationSendingPeriod")) * 1000;
if (opt.equals("Success")) {
String status = "Available";
String DriverAvailable = soapXml
.getDriverChangeStatus(userid, password,
activationid, role, status);
Soap.getSoapResponse(DriverAvailable);
btnWork.setText(finish_work);
btnWork.setBackgroundResource(R.drawable.btn_end);
mHandler.removeCallbacks(mUpdateTimeTask);
mHandler.post(mUpdateTimeTask);
}
} else {
mHandler.removeCallbacks(mUpdateTimeTask);
String DriverChangeStatus = soapXml.getDriverLogOut(
userid, password, activationid, role);
String resp = Soap.getSoapResponse(DriverChangeStatus);
org.w3c.dom.Document doc = XMLfunctions
.XMLfromString(resp);
NodeList nodes = doc.getElementsByTagName("Status");
Element elem = (Element) nodes.item(0);
String opt = XMLfunctions.getValue(elem, "Status");
if (opt.equals("Success")) {
btnWork.setText(start_work);
btnWork.setBackgroundResource(R.drawable.btn_more_yellow);
}
}
// progressHandler.removeCallbacks(progressUpdate);
} catch (Exception e) {
new AlertDialog.Builder(startWork.this)
.setMessage(e.toString())
.setNeutralButton("OK", null).show();
}
progressDialog.dismiss();
}
}).start();
}
public void onLocationChanged(Location location) {
latitude = String.valueOf(location.getLatitude());
longitude = String.valueOf(location.getLongitude());
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
i got following run time exception when click on my startwork button (changeworkstatus function called on click of startwork).
Can't create handler inside thread that has not called Looper.prepare()
so my question is how to solve above error ?
You are doing many things in other thread, then should be event thread, like toast displaying, dismissing dialog, please place your code which need to be in Event thread, in event thread by using either Handler, or Asynctask.

Categories

Resources