Values is not updated after asynchronous task execution in android - java

This is my code in DashBoard_Gujrat Activity
public class DashBoard_Gujrat extends NavigationDrawerActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
inflater = (LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View contentView = inflater
.inflate(R.layout.dashboard_new, null, false);
mDrawerLayout.addView(contentView, 0);
bar = getActionBar();
bar.setDisplayShowHomeEnabled(true);
try {
dbhelper = new DatabaseHelper(this);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bar.setBackgroundDrawable(getResources().getDrawable(
R.drawable.top_header));
yesarrow = (ImageView) findViewById(R.id.yes_arrow);
yes_vehicle = (ImageView) findViewById(R.id.yes_vehicle);
ostwald_bold = Typeface.createFromAsset(getAssets(),
"fonts/Oswald-Bold.otf");
ostwald_regular = Typeface.createFromAsset(getAssets(),
"fonts/Oswald-Regular.otf");
roboto_light = Typeface.createFromAsset(getAssets(),
"fonts/Roboto-Light.ttf");
roboto_regular = Typeface.createFromAsset(getAssets(),
"fonts/Roboto-Regular.ttf");
roboto_thin = Typeface.createFromAsset(getAssets(),
"fonts/Roboto-Thin.ttf");
viewPager = (ViewPager) findViewById(R.id.summarypager);
Ylayout = (LinearLayout) findViewById(R.id.yesLayout);
Yclick = (LinearLayout) findViewById(R.id.yLayout);
Tclick = (LinearLayout) findViewById(R.id.tLayout);
Tlayout = (LinearLayout) findViewById(R.id.toLayout);
first = (ImageView) findViewById(R.id.firstimage);
arrowtrip = (ImageView) findViewById(R.id.ontrip_arrow);
valve6 = (ImageView) findViewById(R.id.valve6);
today = (TextView) findViewById(R.id.todaydate);
yesterday = (TextView) findViewById(R.id.yesterdattxt);
stop = (TextView) findViewById(R.id.stop);
stoptxt = (TextView) findViewById(R.id.stoptxt);
idle = (TextView) findViewById(R.id.idle);
idletxt = (TextView) findViewById(R.id.idletxt);
normal = (TextView) findViewById(R.id.normal);
normaltxt = (TextView) findViewById(R.id.normaltxt);
overspeed = (TextView) findViewById(R.id.overspeed);
overspeedtxt = (TextView) findViewById(R.id.overtxt);
ontriptxt = (TextView) findViewById(R.id.ontripstxt);
km_yesterday = (TextView) findViewById(R.id.km_yesterday);
km_travelled_yesterday = (TextView) findViewById(R.id.KmTravelledYesterday);
vehicle_count_yesterday = (TextView) findViewById(R.id.vehicleCountYesterday);
no_of_trips_yesterday = (TextView) findViewById(R.id.NooftripsYesterday);
km_yestxt = (TextView) findViewById(R.id.km_yesterday);
comp_txt = (TextView) findViewById(R.id.comp_txt);
vehcle_txt = (TextView) findViewById(R.id.vehicle_txt);
stop.setTypeface(roboto_regular);
stoptxt.setTypeface(roboto_regular);
idle.setTypeface(roboto_regular);
idletxt.setTypeface(roboto_regular);
normal.setTypeface(roboto_regular);
normaltxt.setTypeface(roboto_regular);
overspeed.setTypeface(roboto_regular);
overspeedtxt.setTypeface(roboto_regular);
no_of_trips = (TextView) findViewById(R.id.NooftripsToday);
today.setTypeface(roboto_regular);
yesterday.setTypeface(roboto_regular);
ontriptxt.setTypeface(roboto_regular);
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
dateformat = new SimpleDateFormat("dd/MM/yyyy");
formattedDate = df.format(c.getTime());
todayDate = dateformat.format(c.getTime());
today.setText("Today, " + todayDate);
shPreferences = getSharedPreferences(WebServiceHelper.PREFS_NAME, 0);
shEditor = shPreferences.edit();
connectionDetector = new ConnectionDetecter(getApplicationContext());
isInternetPresent = connectionDetector.isConnectingToInternet();
vdetails = new VehicleDetails();
usernameString = shPreferences.getString("Username", "");
telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);// get
IMEI_Number = telephonyManager.getDeviceId();
clientCode = shPreferences.getString("ClientCode", "");
secretCode = shPreferences.getString("SecretCode", "");
callAsynchronousTask();
/*GetYesterdaysSummaryTask yTask = new GetYesterdaysSummaryTask();
yTask.execute();*/
adapter = new MyPagerAdapter();
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
//
device = vd[position].deviceId;
vehicle = vd[position].vehicleNo;
licNo = vd[position].licenseplateNo;
driverId = vd[position].driver_id;
vehicle = vd[position].vehicleId;
driverName = vd[position].driver;
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
gestureDetector = new GestureDetector(this, new MyGestureDetector());
gestureListener = new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
Log.d(WebServiceHelper.TAG, "Gesture Detector------------->");
return gestureDetector.onTouchEvent(event);
}
};
animMoveleft = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.moveleft);
animMoveright = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.moveright);
animLeft = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.move_left);
animRight = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.move_right);
km_travelled_yesterday.setVisibility(View.GONE);
yes_vehicle.setVisibility(View.GONE);
vehcle_txt.setVisibility(View.GONE);
Tclick.startAnimation(animMoveright);
Yclick.startAnimation(animMoveleft);
Ylayout.setOnTouchListener(gestureListener);
Tlayout.setOnTouchListener(gestureListener);
}
/*public void invalidate(){
if(vdetails.outlet_status.contentEquals("1")){
valve6.setImageResource(R.drawable.red_tanker);
}else{
valve6.setImageResource(R.drawable.grenn_tanker);
}
}*/
// get yesterdays summary
public class GetYesterdaysSummaryTask extends
AsyncTask<String, Void, String> {
ProgressDialog Dialog;
#Override
protected void onPreExecute() {
Dialog = new ProgressDialog(DashBoard_Gujrat.this);
Dialog.setMessage(DashBoard_Gujrat.this.getResources().getString(
R.string.loading));
Dialog.setCanceledOnTouchOutside(false);
Dialog.show();
Dialog.setContentView(R.layout.progress);
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String result = "";
// TODO Auto-generated method stub
if (isInternetPresent) {
try {
vdetails = WebServiceHelper.getYesterdaysSummary(
clientCode, secretCode);
} 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();
}
result = "Success";
} else {
result = "Failure";
}
return result;
}
#Override
protected void onPostExecute(String result) {
if (result.contentEquals("Success")) {
if (vdetails.status_login.contentEquals("success")) {
km_travelled_yesterday
.setText(vdetails.distance_travelled_yesterday);
km_travelled_yesterday.setTypeface(ostwald_bold);
vehicle_count_yesterday
.setText(vdetails.vehicle_count_yesterday);
vehicle_count_yesterday.setTypeface(roboto_regular);
no_of_trips_yesterday
.setText(vdetails.completed_trips_yesterday);
no_of_trips_yesterday.setTypeface(roboto_regular);
km_yestxt.setTypeface(roboto_regular);
comp_txt.setTypeface(roboto_regular);
vehcle_txt.setTypeface(roboto_regular);
GetAllvehicleSummarytask gTask = new GetAllvehicleSummarytask();
gTask.execute();
} else {
Toast.makeText(context, "failed", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(context, "No internet", Toast.LENGTH_LONG)
.show();
}
super.onPostExecute(result);
Dialog.dismiss();
}
}
public class GetTodaysSummaryTask extends AsyncTask<String, Void, String> {
ProgressDialog Dialog;
#Override
protected void onPreExecute() {
Dialog = new ProgressDialog(DashBoard_Gujrat.this);
Dialog.setMessage(DashBoard_Gujrat.this.getResources().getString(
R.string.loading));
Dialog.setCanceledOnTouchOutside(false);
Dialog.hide();
Dialog.setContentView(R.layout.progress);
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String result = "";
// TODO Auto-generated method stub
if (isInternetPresent) {
try {
vdetails = WebServiceHelper.getTankerSummary(clientCode,
secretCode);
} 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();
}
result = "Success";
} else {
result = "Failure";
}
return result;
}
#Override
protected void onPostExecute(String result) {
if (result.contentEquals("Success")) {
Log.d(WebServiceHelper.TAG, "On Post Execute------------->");
//callAsynchronousTask();
overspeed.setText(vdetails.overspeed_count);
normal.setText(vdetails.normal_count);
idle.setText(vdetails.idle_count);
stop.setText(vdetails.off_count);
// kmtravelled.setTypeface(roboto_regular);
km_yesterday.setTypeface(roboto_regular);
no_of_trips.setText(vdetails.on_trips_today);
no_of_trips.setTypeface(roboto_regular);
//Tclick.invalidate();
if(vdetails.outlet_status.contentEquals("0")){
Log.d(WebServiceHelper.TAG, "Check Green------------->");
valve6.setImageResource(R.drawable.grenn_tanker);
}else if(vdetails.outlet_status.contentEquals("1")){
Log.d(WebServiceHelper.TAG, "Check Red------------->");
valve6.setImageResource(R.drawable.red_tanker);
callAsynchronousTask();
}
//invalidate();
} else if (result.contentEquals("Failure")) {
Toast.makeText(getApplicationContext(), "No data",
Toast.LENGTH_SHORT).show();
}
super.onPostExecute(result);
Dialog.dismiss();
}
}
private class MyPagerAdapter extends PagerAdapter {
public int getCount() {
return licenseArray.length;
}
public Object instantiateItem(ViewGroup collection, int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View page = inflater.inflate(R.layout.sliding_summary_page, null);
license = (TextView) page.findViewById(R.id.licenseSummary);
license.setTypeface(roboto_regular);
license.setText(licenseArray[position]);
TextView driver = (TextView) page.findViewById(R.id.driverSummary);
ImageView img = (ImageView) page.findViewById(R.id.eng_btn);
driver.setTypeface(roboto_regular);
popup = (ImageView) page.findViewById(R.id.pop_button);
TextView kmtravelledtxt = (TextView) page
.findViewById(R.id.kmtravelledtxt);
kmtravelledtxt.setTypeface(roboto_regular);
driver.setText(driverArray[position]);
TextView km = (TextView) page.findViewById(R.id.kmSummary);
if (KmArray[position].equals("null")) {
km.setText("0");
km.setTypeface(roboto_regular);
} else {
km.setText(KmArray[position]);
km.setTypeface(roboto_regular);
}
TextView loc = (TextView) page.findViewById(R.id.locationSummary);
loc.setText(LocArray[position]);
loc.setTypeface(roboto_regular);
TextView en = (TextView) page.findViewById(R.id.engineSummary);
if (engArray[position].equals("0")) {
img.setImageResource(R.drawable.engine_off);
en.setText("OFF");
en.setTypeface(roboto_regular);
} else {
img.setImageResource(R.drawable.engine_on);
en.setText("ON");
en.setTypeface(roboto_regular);
}
TextView ac = (TextView) page.findViewById(R.id.acSummary);
if (acArray[position].equals("0")) {
ac.setText("OFF");
ac.setTypeface(roboto_regular);
} else {
ac.setText("ON");
ac.setTypeface(roboto_regular);
}
device = vd[0].deviceId;
vehicle = vd[0].vehicleId;
licNo = vd[0].licenseplateNo;
driverId = vd[0].driver_id;
driverName = vd[0].driver;
popup.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
String[] values = new String[] { "Live Tracking",
"Vehicle Profile", "Driver Profile" };
dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.vts_popup);
ListView lv = (ListView) dialog
.findViewById(R.id.list_popupmenu);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
context, android.R.layout.simple_list_item_1,
android.R.id.text1, values) {
#Override
public View getView(int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
View view = super.getView(position, convertView,
parent);
TextView textView = (TextView) view
.findViewById(android.R.id.text1);
/* YOUR CHOICE OF COLOR */
textView.setTextColor(Color.WHITE);
textView.setGravity(Gravity.CENTER);
return view;
}
};
// Assign adapter to ListView
lv.setAdapter(adapter);
// dialog_dismiss=(ImageView)dialog.findViewById(R.id.dialog_dismiss);
dialog.show();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
switch (position) {
case 0: {
Intent moreView = new Intent(context,
Tracking.class);
Bundle bundle = new Bundle();
bundle.putString("device", device);
bundle.putString("vehicle", vehicle);
bundle.putString("License No", licNo);
shEditor.putString("flag", "1").commit();
moreView.putExtras(bundle);
context.startActivity(moreView);
// finish();
break;
}
case 1: {
Intent moreView = new Intent(context,
Vehicle_Profile.class);
Bundle bundle = new Bundle();
bundle.putString("device", device);
bundle.putString("License No", licNo);
bundle.putString("vehicle", vehicle);
shEditor.putString("flag", "1").commit();
moreView.putExtras(bundle);
context.startActivity(moreView);
break;
}
case 2: {
Intent moreView = new Intent(context,
DriverProfile.class);
Bundle bundle = new Bundle();
bundle.putString("driver", driverId);
bundle.putString("DriverName", driverName);
shEditor.putString("flag", "1").commit();
moreView.putExtras(bundle);
context.startActivity(moreView);
break;
}
default:
break;
}
}
});
}
});
((ViewPager) collection).addView(page, 0);
return page;
}
#Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
#Override
public Parcelable saveState() {
return null;
}
}
// webservice call to get all vehicles
public class GetAllvehicleSummarytask extends
AsyncTask<String, Void, String> {
ProgressDialog Dialog;
#Override
protected void onPreExecute() {
Dialog = new ProgressDialog(DashBoard_Gujrat.this);
Dialog.setMessage(DashBoard_Gujrat.this.getResources().getString(
R.string.loading));
Dialog.setCanceledOnTouchOutside(false);
// Dialog.show();
Dialog.setContentView(R.layout.progress);
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String result = "";
if (isInternetPresent) {
try {
vd = WebServiceHelper.getAllvehicleSummary(clientCode,
secretCode, usernameString, IMEI_Number,
formattedDate);
} 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();
}
result = "Success";
} else {
result = "Failure";
}
return result;
}
#Override
protected void onPostExecute(String result) {
if (result.contentEquals("Success")) {
if (VehicleDetails.status_login.equals("success")) {
deviceArray = new String[vd.length];
licenseArray = new String[vd.length];
driverArray = new String[vd.length];
LocArray = new String[vd.length];
KmArray = new String[vd.length];
engArray = new String[vd.length];
acArray = new String[vd.length];
for (int i = 0; i < vd.length; i++) {
licenseArray[i] = vd[i].licenseplateNo;
driverArray[i] = vd[i].driver;
LocArray[i] = vd[i].location_travell;
KmArray[i] = vd[i].km_travelled;
deviceArray[i] = vd[i].deviceId;
engArray[i] = vd[i].en_stat;
acArray[i] = vd[i].ac_stat;
}
viewPager.setAdapter(adapter);
adapter.notifyDataSetChanged();
} else if (VehicleDetails.status_login.equals("failed")) {
Toast.makeText(getApplicationContext(), "No data",
Toast.LENGTH_SHORT).show();
}
} else if (result.contentEquals("Failure")) {
Toast.makeText(getApplicationContext(), "No data",
Toast.LENGTH_SHORT).show();
}
super.onPostExecute(result);
Dialog.dismiss();
}
}
// to get gesture
class MyGestureDetector extends SimpleOnGestureListener {
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
try {
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) {
first.setVisibility(View.VISIBLE);
overspeed.setVisibility(View.VISIBLE);
overspeedtxt.setVisibility(View.VISIBLE);
vehcle_txt.setVisibility(View.GONE);
yesarrow.setVisibility(View.VISIBLE);
/*GetTodaysSummaryTask task=new GetTodaysSummaryTask();
task.execute();*/
km_travelled_yesterday.setVisibility(View.GONE);
yes_vehicle.setVisibility(View.GONE);
// vehcle_txt.setVisibility(View.GONE);
Tclick.startAnimation(animMoveright);
Yclick.startAnimation(animMoveleft);
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
first.setVisibility(View.GONE);
overspeed.setVisibility(View.GONE);
overspeedtxt.setVisibility(View.GONE);
vehcle_txt.setVisibility(View.VISIBLE);
yes_vehicle.setVisibility(View.VISIBLE);
km_travelled_yesterday.setVisibility(View.VISIBLE);
yes_vehicle.setVisibility(View.VISIBLE);
// vehcle_txt.setVisibility(View.GONE);
km_travelled_yesterday.setVisibility(View.VISIBLE);
yesarrow.setVisibility(View.GONE);
Tclick.startAnimation(animLeft);
Yclick.startAnimation(animRight);
}
} catch (Exception e) {
// nothing
}
return false;
}
#Override
public boolean onDown(MotionEvent e) {
return true;
}
}
#Override
public void onBackPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
public void callAsynchronousTask() {
//Log.d(WebServiceHelper.TAG, "Call Async Task>>>>>>>>>>.");
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
if (!isCancelled) {
tTask = new GetTodaysSummaryTask();
tTask.execute();
}
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 2000); // execute in every 5000 ms
// ie in every 5 sec
}
}
Here i used an asynchrous task GetTadaysSummary task to update valve status,trips etc.For automatic updation of values i call the GetTodaysSummaryTask using callasynchronous() method using timer in every 5 seconds.But on live testing the values in the from the GetTodaysSummaryTask is not automatically updated.It only changed when we relaunched the activity.
I dont know what the problem.Please help me.thanks in advance.If anything wrong in my question please forgive me.

Seems like you start your ASyncTask from a non UI Thread(here = TimerTask Runnable). As far as I know ASyncTask is designed to run on UI Thread, only the doInBackground() method runs in a seperate Thread.
Check this question/answer, for further information:
Start AsyncTask in TimerTask
I also noticed
if (VehicleDetails.status_login.equals("success"))
cant find the string "success" is initialized anywhere in your code, only a "Success" with capital S...

Related

Performing filtered search in android actionbar over a listview

I am trying to create a search view in the action bar of my app, which will perform search (that is will display the names of items from the listview according to the letter typed) over a listview in the app. Listview uses a listadapter class. When I enter text in the search view, nothing happens. I am quite new with search view, tried to use the codes got from the net but that didn't help. :( Can you please suggest me over how to do this? Should I create another class for it?
Here is my code:
ListAdapter.java
public class ListAdapter extends BaseAdapter{
Vector listData = null;
public void setData(Vector data) {
listData = data;
}
private Context _context;
private List<String> list;
ViewHolder holder=null;
View row=null;
public ListAdapter(Context _context,List<String> list)
{
this._context=_context;
this.list=list;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return list.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
private static class ViewHolder
{
public TextView textView;
public ViewHolder(View row) {
// TODO Auto-generated constructor stub
textView = (TextView) row.findViewById(R.id.rowTextView);
}
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
// TODO Auto-generated method stub
row=convertView;
holder=null;
try{
if(row==null)
{
LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.simplerow, viewGroup, false);
holder=new ViewHolder(row);
row.setTag(holder);
Log.d("newrow", "New row");
/*/View row = convertView;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.simplerow, viewGroup, false);
}
TextView textView = (TextView) row.findViewById(R.id.rowTextView);*/
holder.textView.setText(list.get(position).toString());
}
else
{
holder= (ViewHolder) row.getTag();
Log.d("recycle", "Recycling stuff");
}
}
catch(Exception e)
{
e.printStackTrace();
}
try
{
if(row!=null)
{
if(position==MainActivity.selected_item)
{
row.setBackgroundColor(Color.RED);
}
else
{
row.setBackgroundColor(Color.BLACK);
}
}
}
catch(Exception e)
{
}
return row;
}
public Filter getFilter() {
// TODO Auto-generated method stub
return null;
}
}
MainActivity.java
public class MainActivity extends Activity implements View.OnClickListener, OnCompletionListener {
ListView list;
ArrayAdapter<String> adapter ;
ListAdapter listAdapter;
ArrayList<String> listTest;
ArrayList<String> listSoundNames;
ImageButton play,stop,back,next;
String songpath,song,title;
int index,current_position;
File[] listFile;
SharedPreferences sharedPref;
MediaPlayer mp,mp2;
ActionBar bar;
private Boolean state=false;
private static int save = -1;
int count=0;
private static final String TAG = MainActivity.class.getSimpleName();
private Context _context = this;
public static int selected_item=-1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
song = sharedPref.getString("songname", "name");
mp=new MediaPlayer();
mp2 = new MediaPlayer();
mp.setOnCompletionListener(this);
list = (ListView)findViewById(R.id.list);
//list.setTextFilterEnabled(true);
list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
_context=this;
adapter = new ArrayAdapter<String>(_context,R.layout.simplerow, listSoundNames);
listTest = new ArrayList<String>( );
listSoundNames=new ArrayList<String>();
play = (ImageButton)findViewById(R.id.play);
back = (ImageButton)findViewById(R.id.prev);
next = (ImageButton)findViewById(R.id.next);
//adding listeners
play.setOnClickListener(this);
back.setOnClickListener(this);
next.setOnClickListener(this);
//action bar controls
bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#DF0174")));
//bar.setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
EditText editText = new EditText(getApplicationContext());
getActionBar().setCustomView(editText);
//bar.setDisplayShowTitleEnabled(true);
//bar.setDisplayHomeAsUpEnabled(true);
Scanner("/sdcard/");//storage path
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////*Adding listener to songs*//////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if(listTest.size() != 0)
{
//listAdapter = new ArrayAdapter<String> (MainActivity.this,R.layout.simplerow, listSoundNames);
listAdapter=new ListAdapter(_context,listSoundNames);
list.setAdapter(listAdapter);
list.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
//////////////////changing list item background on click///////////////////
//list.setSelection(position);
view.setSelected(true);
///////////////////PROBLEM/////////////
for(int a = 0; a < parent.getChildCount(); a++)
{
list.clearChoices();
parent.getChildAt(a).setBackgroundColor(Color.BLACK);
}
selected_item=position;
// view.setBackgroundColor(Color.RED);
////////////////////////////////////////////////////////////////////////////
//accessing song path
String selected = listTest.get(position);
list.setItemChecked(position, true);
list.setSelection(position);
//accessing the song name
String name = (String) ((TextView) view).getText();
title = name;
//bar.setTitle(title);
//Log.e(TAG, name);
Toast.makeText(getApplicationContext(), name, Toast.LENGTH_SHORT).show();
try{
mp.reset();
mp.setDataSource(listTest.get(position));//source
mp.prepare();
mp.start();
index = position;
play.setImageResource(R.drawable.pause);
}
catch(Exception e){e.printStackTrace();}
}
});
}
}
////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////*Songs added here to list*////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
private void Scanner(String path) {
// TODO Auto-generated method stub
{
try
{
File fl = new File(path);
File[] listOfFiles = fl.listFiles();
for (File listOfFile : listOfFiles)
{
String s = listOfFile.getName();
if(s.endsWith(".mp3"))
{
songpath = listOfFile.getPath();
listTest.add(songpath);//adding song names to list
//listTest.toString().replaceFirst(songpath, s);
// store file name in listSoundNames
int pos = s.lastIndexOf(".");
if (pos > 0)
{
song = s.substring(0, pos);
}
listSoundNames.add(song);
}
/////////////////////////////////
File f = new File(path+s+"/");
if (f.exists() && f.isDirectory()) {
Scanner(path+s+"/");
}
////////////////////////////////
}
}
catch (Exception e) { }
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.equals(play))
{
if(mp.isPlaying())
{
mp.pause();
Toast.makeText(MainActivity.this, "paused", Toast.LENGTH_SHORT).show();
//change in button image//
play.setImageResource(R.drawable.play);
}
else
{
mp.start();
Toast.makeText(MainActivity.this, "started", Toast.LENGTH_SHORT).show();
//change in button image//
play.setImageResource(R.drawable.pause);
//
}
}
if (v.equals(back))
{
mp.stop();
mp.reset();
//bar.setTitle(song);
if(index!=0)
{
index = index -1;
}
else
{
index = (list.getAdapter().getCount()-1)-1;
}
Uri uri = Uri.parse(listTest.get(index).toString());//getting the path of next song
try {
mp.setDataSource(getApplicationContext(), uri);//setting new data source
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(MainActivity.this, "ERROR", Toast.LENGTH_SHORT).show();///PROBLEM:MOVING HERE AFTER CLICKING NEXT BUTTON
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();//PROBLEM: NOT PLAYING
Toast.makeText(MainActivity.this, ""+uri, Toast.LENGTH_SHORT).show();
}
if (v.equals(next))
{
mp.stop();
mp.reset();
index = index +1;
Uri uri = Uri.parse(listTest.get(index).toString());//getting the path of next song
try {
mp.setDataSource(getApplicationContext(), uri);//setting new data source
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(MainActivity.this, "ERROR", Toast.LENGTH_SHORT).show();///PROBLEM:MOVING HERE AFTER CLICKING NEXT BUTTON
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();//PROBLEM: NOT PLAYING
Toast.makeText(MainActivity.this, ""+uri, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
play.setImageResource(R.drawable.play);
}
/*#Override
protected void onStop() {
super.onStop();
mp.stop();
Toast.makeText(getApplicationContext(), "stopped", Toast.LENGTH_LONG).show();
}*/
//////////////////////////////////////////Search box/////////////////////////////////////////////////////
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false);
searchView.setQueryHint(Html.fromHtml(("<font color = #ffffff>"+"Listen Now"+"</font>")));
SearchView.OnQueryTextListener textChangeListener = new SearchView.OnQueryTextListener()
{
#Override
public boolean onQueryTextChange(String newText)
{
// this is your adapter that will be filtered
//listAdapter.getFilter().filter(newText);
Toast.makeText(getApplicationContext(), "type"+newText, Toast.LENGTH_SHORT).show();
return true;
}
#Override
public boolean onQueryTextSubmit(String query)
{
// this is your adapter that will be filtered
//((Filterable) listAdapter).getFilter().filter(query);
//listAdapter.getFilter().filter(query);
Toast.makeText(getApplicationContext(), query, Toast.LENGTH_SHORT).show();
/* try
{
File fl = new File("/sdcard/");
File[] listOfFiles = fl.listFiles();
String selectedPath="";
for (File listOfFile : listOfFiles)
{
String s = listOfFile.getName();
if(s.equalsIgnoreCase(query) && s.endsWith(".mp3"))
{
selectedPath= listOfFile.getPath();//not receiving the path:PROBLEM:HOLDING THE POSITION FOR LIST ITEM
//listTest.add(songpath);//adding song names to list
//listTest.toString().replaceFirst(songpath, s);
Toast.makeText(getApplicationContext(), listOfFile.getPath(), Toast.LENGTH_SHORT).show();
/*mp.setDataSource(selectedPath);
mp.prepare();
mp.start();
}
/////////////////////////////////
File f = new File("/sdcard/"+s+"/");
if (f.exists() && f.isDirectory()) {
Scanner("/sdcard/"+s+"/");
}
////////////////////////////////
}
}
catch (Exception e) { }*/
return true;
}
};
searchView.setOnQueryTextListener(textChangeListener);
return super.onCreateOptionsMenu(menu);
}
}
Screenshots:
1) In your layout.xml:
<android.support.v7.widget.SearchView
android:id="#+id/mSearchView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:searchIcon="#android:drawable/ic_menu_search"
app:defaultQueryHint="#string/search_hint"/>
2) Declare SearchView searchView; in global scope (outside every function).
3) set the reference of your layout widget searchView = (SearchView) view.findViewById(R.id.mSearchView); in any function/method you like, where you initialize your views.
4) and then add this code in whatever function/method you like :
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// your code when you submit your search
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
// your code when you type on your searchview
return true;
}
});
This is how to implement searchView.

Why is there too much work on main thread?

So I'm trying to make a simple application that makes stores group events in a MySQL database then retrieves them for people to join. In this fragment I list all the events by using a JSONParser class to query the database. I use an Async class to do the querying. The fragment will initially query the db on startup or whenever the user decides to limit the scope of the events by selecting something in a spinner or when the user pushes a refresh button. I have been getting messages like
Choreographer﹕ Skipped 95 frames! The application may be doing too much work on its main thread.
while running the program and I'm not sure why. I think it might be because I call the Async class too much, but I'm not sure.
public class mainActivityFragment extends Fragment {
final public String information = "information";
public Spinner specifySubject;
private ArrayList<String> list = new ArrayList<>();
private ArrayList<EventObject> eventList = new ArrayList<>();
JSONParser jsonParser = new JSONParser();
ListView test;
ArrayAdapter adapter;
// url to create new product
private static String url_get_event = "";
private ProgressDialog pDialog;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_main, container, false);
adapter = new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1, list);
test = (ListView) v.findViewById(R.id.listView);
new CreateNewProduct().execute();
if(pDialog.isShowing()){
pDialog.dismiss();
}
test.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
Intent in = new Intent(getActivity(), AttendInformation.class);
EventObject clickedEvent = eventList.get(position);
String[] testInformation = {clickedEvent.getTo().toString(), clickedEvent.getLocation(), clickedEvent.getTitle(), clickedEvent.getDurationString(), clickedEvent.getDescription(), clickedEvent.getSubject()};
in.putExtra(information, testInformation);
startActivity(in);
}
});
Button createEventButton = (Button) v.findViewById(R.id.Button2);
createEventButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent in = new Intent(getActivity(), createEvent.class);
startActivity(in);
}
});
specifySubject = (Spinner) v.findViewById(R.id.spinner);
specifySubject.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
AsyncTask task;
task = new CreateNewProduct().execute();
try {
task.get(3000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
if (position == 0) {
} else {
String selectedSubj = getResources().getStringArray(R.array.class_array)[position];
for (int i = 0; i < eventList.size(); i++) {
if (!eventList.get(i).getSubject().equals(selectedSubj)) {
list.remove(list.indexOf(eventList.get(i).getTitle()));
eventList.remove(i);
i--;
}
}
adapter.notifyDataSetChanged();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Button refresh = (Button) v.findViewById(R.id.leftButton);
refresh.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AsyncTask task;
task = new CreateNewProduct().execute();
try {
task.get(3000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
if (specifySubject.getSelectedItemPosition() == 0) {
} else {
String selectedSubj = getResources().getStringArray(R.array.class_array)[specifySubject.getSelectedItemPosition()];
for (int i = 0; i < eventList.size(); i++) {
if (!eventList.get(i).getSubject().equals(selectedSubj)) {
list.remove(list.indexOf(eventList.get(i).getTitle()));
eventList.remove(i);
i--;
}
}
adapter.notifyDataSetChanged();
}
}
});
return v;
}
class CreateNewProduct extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Getting Events...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
JSONArray jsonArr = jsonParser.getJSONFromUrl(url_get_event);
for(int n = 0; n < jsonArr.length(); n++)
{
try {
JSONObject object = jsonArr.getJSONObject(n);
if(!list.contains(object.getString("title"))){
String[] time = object.getString("time").split(":");
time[1] = time[1].substring(0, 2);
EventObject tempEven = new EventObject(object.getString("title"), object.getString("location"), object.getString("description"), object.getString("subject"), 0, new TimeObject(Integer.parseInt(time[0]), Integer.parseInt(time[1])));
eventList.add(tempEven);
list.add(object.getString("title"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
test.setAdapter(adapter);
pDialog.dismiss();
}
}
}

Android : getParams() called two times dont know why?

Here getParams() method called two times and added two times data at my server. I have also noticed that my logs print twice in logcat. It occurs when I check two checkbox of from contact picker list view to send data to server.
Here is my json data :
{
"send_data":[{
"gcm_reg_id":
"APA91bFPfAvEL_UJRHiOSohkekTh7M9qj1Kj307kFqmWh4VS8Re1aeejWSKXQnJb7q3OIjykCccbbI-0pn14DwvyjjL4ynQTHNR-m1p3vxLKy7ujGXv2MpIe0fhT2vcTJE0SW0uTjkD9iPJz0pw3sMuGojA4yxw0zg", "receiver_id":
"170"
},{
"gcm_reg_id":
"APA91bFheDJdBe3LwBk7MNchLitnKkECgVARxopr0HnFemo1vfW3Q0Mt1m6GXxccoq-wjUwoV-yXOVvcw9JwXcOZwAPyal9ZqMoA-U3fLNdaMa7pu8f-GYSyMsv16XKkgzPpzOPPKs8pc9C-7K1MhZXKgRf67DiXTSRY67swIOGP1XmJyoa3l1s", "receiver_id":
"166"
}]
}
Here is my code :
public class ContacsPicker extends ListActivity implements OnClickListener{
ProgressDialog dialog;
ConnectionDetector cd;
String phoneNumber ;
String conatct_num;
ArrayList<integer> status;
ImageView iv;
ArrayList<PhoneContactInfo> list;
JSONArray contact_noArray;
ArrayList<String> contact_database;
ArrayList<String> contact_userid;
ArrayList<String> image;
ListView list_view;
CustomListViewAdapter adpter;
String user_id,message,level,time,image_name,receiver_id,regId,mail;
Bitmap send_image;
Store_pref obj_Store_pref;
RegisterUser obj_RegisterUser;
ProgressDialog Dialog;
EditText edt_search;
ImageView iv_search;
RelativeLayout relative_search;
Boolean is_serch=false;
Matrix matrix = new Matrix();
send_data obj_Send_data;
String sender_regid,ba1, data;
Context mContext;
public Uri targetUri;
JSONObject obj;
Button button1_send;
ArrayList<String> checkedValue;
ArrayList<send_data> id_arrArrayList;
List<com.waycreon.picture_puzzle.model.RegisterUser.Registure_user> Registure_user;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts_picker);
mContext=this;
edt_search =(EditText) findViewById(R.id.edt_search);
iv_search=(ImageView)findViewById(R.id.iv_search);
button1_send=(Button) findViewById(R.id.button1_send);
button1_send.setOnClickListener(this);
relative_search=(RelativeLayout)findViewById(R.id.relative_search);
set_invisible_relative_search();
obj_Store_pref=new Store_pref(ContacsPicker.this);
regId=obj_Store_pref.get_GCMreg_id();
mail=obj_Store_pref.get_mail_id();
Log.i("GCM reg id in contact picker class", "++++"+regId);
Log.i("mail id in contact picker class", "++++"+mail);
iv_search.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(!is_serch)
{
is_serch=true;
search_click();
}
else
{
is_serch=false;
close_click();
}
}
});
list_view=getListView();
message = getIntent().getStringExtra("message");
level = getIntent().getStringExtra("level");
time = getIntent().getStringExtra("time");
targetUri= (Uri) getIntent().getParcelableExtra("targetUri");
Log.i("get message", message);
Log.i("get level", level);
Log.i("get time", time);
Log.i("get send_image", send_image+"=");
Log.i("target uri", ""+targetUri);
try {
int orientation = getOrientation(this, targetUri);
Log.i("orientation on create", "++"+orientation);
matrix.postRotate(orientation);
send_image = MediaStore.Images.Media.getBitmap(this.getContentResolver(), targetUri);
send_image= get_Resized_Bitmap(send_image,600,800);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
send_image.compress(Bitmap.CompressFormat.JPEG, 100, bao);
byte [] ba = bao.toByteArray();
ba1=Base64.encodeToString(ba,1);
Log.i("base 64", ba1);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
status=new ArrayList<integer>();
contact_database=new ArrayList<String>();
contact_userid=new ArrayList<String>();
image=new ArrayList<String>();
cd=new ConnectionDetector(this);
obj_Store_pref= new Store_pref(this);
dialog = new ProgressDialog(ContacsPicker.this);
dialog.setCancelable(false);
dialog.setMessage("Please Wait...");
dialog.setCancelable(false);
list = getAllPhoneContacts();
get_registered_no();
edt_search = (EditText) findViewById(R.id.edt_search);
edt_search .addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = edt_search .getText().toString()
.toLowerCase(Locale.getDefault());
adpter.filter(text);
list_view.setAdapter(adpter);
adpter.notifyDataSetChanged();
}
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
public void onTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
});
id_arrArrayList=new ArrayList<send_data>();
list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
CheckBox cb = (CheckBox) arg1.findViewById(R.id.checkBox1_check);
cb.performClick();
receiver_id =arg1.getTag().toString();
// String gcm_reg_id=Registure_user.get(arg2).gcm_regid;
// Log.i("gcm_reg id on list click", gcm_reg_id);
Log.i("in if", receiver_id+"++++");
if(!arg1.getTag().equals("0"))
{
String[] separated = arg1.getTag().toString().split(" ");
String receiver_id =separated[0];
String gcm_reg_id=separated[1];
if (cb.isChecked()) {
Log.i("in if check box", receiver_id+"++++");
obj_Send_data = new send_data();
obj_Send_data.setReceiver_id(receiver_id);
obj_Send_data.setGcm_reg_id(gcm_reg_id);
id_arrArrayList.add(obj_Send_data);
Log.i("arraylist in if lisze", "++"+ id_arrArrayList.size());
} else if (!cb.isChecked()) {
id_arrArrayList.remove(obj_Send_data);
Log.i("arraylist in else lisze", "++"+ id_arrArrayList.size());
}
}
// if(!arg1.getTag().equals("0"))
// {
// receiver_id =arg1.getTag().toString();
// show_alert_invitation("Invitation","Are you sure you want to send puzzle to your friend ?");
//
// Log.i("in if ", receiver_id+"++++");
//
// Get_receiver_reg_id();
//
//
// }
// else
// {
// show_alert_unregister_user("Notification",getString(R.string.unregister_user_message));
// }
}
});![enter image description here][1]
}
public void onClick(View v) {
if(v==button1_send)
{
// Log.i("array list", receiver_id);
// Send_data();
show_alert_invitation("Invitation","Are you sure you want to send task to your friend ?");
}
}
private void get_registered_no() {
// TODO Auto-generated method stub
if (cd.isConnectingToInternet())
{
dialog.show();
RequestQueue queue = Volley.newRequestQueue(ContacsPicker.this);
String url="http://karmamobichamps.com/Restaurant_app/puzzle/puzzle_app_services.php?do=get_registered_no";
Log.i("url", url+"+++++++++++");
StringRequest myReq = new StringRequest(Method.GET,url,
Get_Event_list_ReqSuccessListener(),
Get_Event_list_ReqErrorListener());
queue.add(myReq);
}
else
{
cd.show_alert("no connection", "Please check with your internet Connection");
}
}
private ErrorListener Get_Event_list_ReqErrorListener() {
return new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
Log.i("Volly err", error.getLocalizedMessage()+"++++");
error.printStackTrace();
}
};
}
private Listener<String> Get_Event_list_ReqSuccessListener() {
return new Response.Listener<String>() {
public void onResponse(String response) {
dialog.dismiss();
Log.i("registration data", response+"");
try {
JSONObject jo=new JSONObject(response);
if(jo.getString("ResponseCode").equals("1"))
{
try
{
Gson gson = new GsonBuilder().create();
obj_RegisterUser= gson.fromJson(response, RegisterUser.class);
Registure_user=obj_RegisterUser.Registure_user;
Log.i("user size", Registure_user.size()+"--");
}
catch (Exception e) {
e.printStackTrace();
}
}
} catch (JSONException e1) {
e1.printStackTrace();
}
for(int i=0;i<list.size();i++)
{
image.add("0");
}
for(int i=0;i<list.size();i++)
{
for(int j=0;j<Registure_user.size();j++)
{
String[] separated = Registure_user.get(j).mobile_no.split(" ");
String mobilenono = separated[separated.length-1];
String country_code = separated[0];
// String mobilenono=separated[1];
String mobile_no=country_code+mobilenono;
if(list.get(i).getcontactNumber().equals(mobilenono) || list.get(i).getcontactNumber().equals(mobile_no) ||(list.get(i).getcontactNumber().equals(Registure_user.get(j).mobile_no)) ||list.get(i).getcontactNumber().equals("0"+mobilenono)) {
image.set(i,Registure_user.get(j).id.toString()+" "+Registure_user.get(j).gcm_regid.toString());
Log.i("match", list.get(i).getcontactNumber()+"==");
}
}
}
adpter=new CustomListViewAdapter(ContacsPicker.this, list,Registure_user,image);
list_view.setAdapter(adpter);
}
};
}
private void Send_data() {
data=Write_json();
Log.i("in send data method", data);
Dialog=new ProgressDialog(this);
Dialog.setTitle("sending..");
Dialog.setCancelable(false);
Dialog.show();
RequestQueue queue = Volley.newRequestQueue(ContacsPicker.this);
String url = null;
url = "http://karmamobichamps.com/Restaurant_app/puzzle/send_multi_data.php" ;
StringRequest myReq = new StringRequest(Method.POST,url,
send_data_ReqSuccessListener(),
send_data_ReqErrorListener())
{
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
// HashMap<String, String> params = new HashMap<String, String>();
// {
**params.put("data", data);
params.put("image", ba1);
params.put("sender_id", obj_Store_pref.get_user_id());
params.put("message", message);
params.put("level",level);
params.put("time", time);
params.put("status", "1");
Log.i("data in params", data);
Log.i("sender_id in params", obj_Store_pref.get_user_id());
Log.i("level",level);
Log.i("message in params", message);
Log.i("time in params", time);
Log.i("status in params", "1");**
return params;
};
};
queue.add(myReq);
}
private ErrorListener send_data_ReqErrorListener() {
return new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
Dialog.dismiss();
Log.i("Volly err", error.getLocalizedMessage()+"++++");
error.printStackTrace();
}
};
}
private Listener<String> send_data_ReqSuccessListener() {
return new Response.Listener<String>() {
public void onResponse(String response) {
Dialog.dismiss();
Log.i("registration data", response+"");
try {
JSONObject jo=new JSONObject(response);
if (jo.getString("ResponseCode").equals("1")) {
finish();
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
};
}
private void send_to_web() {
// TODO Auto-generated method stub
final String URL = "http://karmamobichamps.com/Restaurant_app/puzzle/send_multi_data.php";
// Post params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("data", data);
// params.put("image", ba1);
// params.put("sender_id", obj_Store_pref.get_user_id());
// params.put("message", message);
// params.put("level",level);
// params.put("time", time);
// params.put("status", "1");
JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
ApplicationController.getInstance().addToRequestQueue(req);
}
private void show_alert_invitation(String title,String msg) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle(title)
.setMessage(msg)
.setCancelable(false)
.setPositiveButton("Ok",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// new ImageUpload().execute();
Send_data();
// send_to_web();
Log.i("bitmap width in contact picker", ""+send_image.getWidth());
Log.i("bitmap height in contact picker", ""+send_image.getHeight());
dialog.cancel();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
private void show_alert_unregister_user(String title,String msg) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle(title)
.setMessage(msg)
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, "Swapatask");
String sAux = "\nHeyy use this amazing application i m using too...\n\n";
sAux = sAux + "https://play.google.com/store/apps/details?id=com.waycreon.picture_puzzle \n\n";
i.putExtra(Intent.EXTRA_TEXT, sAux);
startActivity(Intent.createChooser(i, "choose one"));
}
})
.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
}
private void set_visible_relative_search() {
relative_search.setVisibility(RelativeLayout.VISIBLE);
}
private void set_invisible_relative_search() {
relative_search.setVisibility(RelativeLayout.GONE);
}
private void search_click() {
iv_search.setImageResource(R.drawable.close);
set_visible_relative_search();
edt_search.setFocusable(true);
}
private void close_click() {
iv_search.setImageResource(R.drawable.search_button);
set_invisible_relative_search();
edt_search.setText("");
}
/*============================get local to phone all contect===================================*/
public ArrayList<PhoneContactInfo> getAllPhoneContacts() {
Log.d("START","Getting all Contacts");
ArrayList<PhoneContactInfo> arrContacts = new ArrayList<PhoneContactInfo>();
PhoneContactInfo phoneContactInfo=null;
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
Cursor cursor = getContentResolver().query(uri, new String[] {ContactsContract.CommonDataKinds.Phone.NUMBER,ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,ContactsContract.CommonDataKinds.Phone._ID}, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
cursor.moveToFirst();
while (cursor.isAfterLast() == false)
{
String contactNumber= cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
int phoneContactID = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
if (contactNumber.length()>0)
{
phoneContactInfo = new PhoneContactInfo();
phoneContactInfo.setphoneContactID(phoneContactID);
phoneContactInfo.setcontactName(contactName);
phoneContactInfo.setcontactNumber(contactNumber.replaceAll("\\s+",""));
arrContacts.add(phoneContactInfo);
}
phoneContactInfo = null;
cursor.moveToNext();
}
cursor.close();
cursor = null;
Log.d("END","Got all Contacts");
return arrContacts;
}
private void Send_push() {
// Dialog.show();
RequestQueue queue = Volley.newRequestQueue(ContacsPicker.this);
String url = null;
try {
url = "http://karmamobichamps.com/Restaurant_app/puzzle/puzzle_app_services.php?do=Receive_Push_notification&gcm_regid="
+sender_regid+"&message="+URLEncoder.encode("You Have Received Swapatask Request", "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i("rgister url", url);
StringRequest myReq = new StringRequest(Method.GET,url,
Registration_ReqSuccessListener(),
Registration_ReqErrorListener());
queue.add(myReq);
}
private ErrorListener Registration_ReqErrorListener() {
return new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
// Dialog.dismiss();
Log.i("Volly err", error.getLocalizedMessage()+"++++");
error.printStackTrace();
}
};
}
private Listener<String> Registration_ReqSuccessListener() {
return new Response.Listener<String>() {
public void onResponse(String response) {
// Dialog.dismiss();
Log.i("registration data", response+"");
//
}
};
}
public Bitmap get_Resized_Bitmap(Bitmap bmp, int newHeight, int newWidth) {
int width = bmp.getWidth();
int height = bmp.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// CREATE A MATRIX FOR THE MANIPULATION
// Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);
// matrix.postRotate(90);
// "RECREATE" THE NEW BITMAP
Bitmap newBitmap = Bitmap.createBitmap(bmp, 0, 0, width, height, matrix, true);
return newBitmap ;
}
public static int getOrientation(Context context, Uri photoUri) {
/* it's on the external media. */
Cursor cursor = context.getContentResolver().query(photoUri,
new String[] { MediaStore.Images.ImageColumns.ORIENTATION }, null, null, null);
if (cursor.getCount() != 1) {
return -1;
}
cursor.moveToFirst();
return cursor.getInt(0);
}
private String Write_json() {
// TODO Auto-generated method stub
Log.i("arraylist lisze in next button", "++"+ id_arrArrayList.size());
obj = new JSONObject();
JSONArray list1 = new JSONArray();
try {
for (int i = 0; i < id_arrArrayList.size(); i++) {
String gcm_reg_id=Registure_user.get(i).gcm_regid;
JSONObject jsonObject=new JSONObject();
jsonObject.put("receiver_id", id_arrArrayList.get(i).getReceiver_id());
jsonObject.put("gcm_reg_id", id_arrArrayList.get(i).getGcm_reg_id());
Log.i("gcm_reg_id", gcm_reg_id);
list1.put(jsonObject);
}
obj.put("send_data", list1);
}catch (Exception e) {
e.printStackTrace();
}
return obj.toString();
}
// public class ImageUpload extends AsyncTask<String, String,String>
// {
// Bitmap bitmap;
// public ImageUpload()
// {
// // TODO Auto-generated constructor stub
//// this.bitmap=bitmap;
// }
// #Override
// protected void onPreExecute()
// {
// dialog.show();
// super.onPreExecute();
//
// }
// #Override
// protected String doInBackground(String... params)
// {
// // TODO Auto-generated method stub
// try
// {
//// ByteArrayOutputStream bao = new ByteArrayOutputStream();
//// bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bao);
//// byte [] ba = bao.toByteArray();
//// String ba1=Base64.encodeToString(ba,1);
// Log.i("base 64", ba1);
// ArrayList<NameValuePair> nameValuePairs = new enter code hereArrayList<NameValuePair>();
// HttpClient httpclient = new DefaultHttpClient();
// HttpPost httppost = new HttpPost("http://karmamobichamps.com/Restaurant_app/puzzle/send_multi_data.php");
// Log.i("url", ""+httppost);
// nameValuePairs.add(new BasicNameValuePair("data", data));
// nameValuePairs.add(new BasicNameValuePair("image", ba1));
// nameValuePairs.add(new BasicNameValuePair("sende
To identify the root of this issue you'll need to debug and see what's the path in which getParams is called.
You could either breakpoint within getParams block or print the stack trace to log like so:
Throwable throwable = new IllegalArgumentException("Something");
throwable.printStackTrace();
Add this before adding request to request queue
request.setRetryPolicy(new DefaultRetryPolicy(
0,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

How can i capture image with a touch on surface view

public class AndroidCamera extends Activity implements OnTouchListener, SurfaceHolder.Callback{
Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean previewing = false;;
PictureCallback rawCallback;
ShutterCallback shutterCallback;
PictureCallback jpegCallback;
EditText txtData, Info,Age;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonStartCameraPreview = (Button)findViewById(R.id.startcamerapreview);
Button buttonStopCameraPreview = (Button)findViewById(R.id.stopcamerapreview);
Button buttonCapturePreview = (Button) findViewById(R.id.capturepreview);
txtData = (EditText) findViewById(R.id.editText1);
Info = (EditText) findViewById(R.id.Name);
Info.setHint("enter name");
Age = (EditText) findViewById(R.id.Age);
Age.setHint("Age");
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView)findViewById(R.id.surfaceview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
rawCallback = new PictureCallback()
{
public void onPictureTaken(byte[] data, Camera camera)
{
Log.d("Log", "onPictureTaken - raw");
}
};
shutterCallback = new ShutterCallback()
{
public void onShutter() {
Log.i("Log", "onShutter'd");
}
};
// onTouchEvent(null);
jpegCallback = new PictureCallback()
{
public void onPictureTaken(byte[] data, Camera camera)
{
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "Asw");
imagesFolder.mkdirs();
Date d = new Date();
CharSequence s = DateFormat.format("MM-dd-yy hh-mm-ss", d.getTime());
File output = new File(imagesFolder, s.toString() + ".jpg");
Uri uriSavedImage = Uri.fromFile(output);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriSavedImage);
imageFileOS.write(data);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(AndroidCamera.this,
"Image saved: ",
Toast.LENGTH_LONG).show();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{}
Log.d("Log", "onPictureTaken - jpeg");
}
};
buttonStartCameraPreview.setOnClickListener(new Button.OnClickListener()
{
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
public void onClick(View v)
{
if(!previewing)
{
camera = Camera.open(0);
if (camera != null)
{
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
}
catch (IOException e)
{
e.printStackTrace();
}
}else txtData.setText("null");
}
}});
buttonCapturePreview.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
captureImage();
}
private void captureImage()
{
camera.takePicture(shutterCallback, rawCallback, jpegCallback);
}
});
buttonStopCameraPreview.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v)
{
if(camera != null && previewing)
{
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
}});
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.android_camera, menu);
return true;
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height)
{
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder holder)
{
// TODO Auto-generated method stub
}
#Override
public void surfaceDestroyed(SurfaceHolder holder)
{
// TODO Auto-generated method stub
}
public boolean onTouch(View v, MotionEvent event)
{
if (event.getAction() == MotionEvent.ACTION_MOVE)
{
camera.takePicture(shutterCallback, rawCallback, jpegCallback);
}
return super.onTouchEvent(event);
//return false;
}
I have used a button to capture the image. Now i wanted to capture and save the image with just a touch on surface view. I wrote some code.Its not showing any error but it is not working also. Could you please tell me where i am going wrong. Please help
Try this to take screen shot programmatically...
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + ACCUWX.IMAGE_APPEND;
// create bitmap screen capture
Bitmap bitmap;
View v1 = mCurrentUrlMask.getRootView();
v1.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
OutputStream fout = null;
imageFile = new File(mPath);
try {
fout = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
fout.flush();
fout.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public class SnapShot extends Activity implements OnClickListener,
SurfaceHolder.Callback, Camera.PictureCallback {
SurfaceView cameraView;
SurfaceHolder surfaceHolder;
Camera camera;
LayoutInflater inflater;
Uri imageFileUri;
Button save;
Button retry;
View viewControl;
LayoutParams layoutParamsControl;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_camera);
cameraView = (SurfaceView) this.findViewById(R.id.CameraView);
surfaceHolder = cameraView.getHolder();
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
surfaceHolder.addCallback(this);
cameraView.setFocusable(true);
cameraView.setFocusableInTouchMode(true);
cameraView.setClickable(true);
cameraView.setOnClickListener(this);
inflater = LayoutInflater.from(getBaseContext());
viewControl = inflater.inflate(R.layout.camera_control, null);
save = (Button) viewControl.findViewById(R.id.vc_btn_keep);
retry = (Button)viewControl.findViewById(R.id.vc_btn_discard);
layoutParamsControl = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
camera.startPreview();
}
public void surfaceCreated(SurfaceHolder holder) {
camera = Camera.open();
try {
Camera.Parameters parameters = camera.getParameters();
if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
// This is an undocumented although widely known feature
parameters.set("orientation", "portrait");
// For Android 2.2 and above
camera.setDisplayOrientation(90);
// Uncomment for Android 2.0 and above
// parameters.setRotation(90);
} else {
// This is an undocumented although widely known feature
parameters.set("orientation", "landscape");
// For Android 2.2 and above
camera.setDisplayOrientation(0);
// Uncomment for Android 2.0 and above
// parameters.setRotation(0);
}
camera.setParameters(parameters);
camera.setPreviewDisplay(holder);
} catch (IOException exception) {
camera.release();
Log.v("surfaceCreated", exception.getMessage());
}
camera.startPreview();
}
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
}
#Override
public void onPictureTaken(final byte[] data, Camera camera) {
this.addContentView(viewControl, layoutParamsControl);
save.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
insertImage(data);
Intent i = new Intent();
i.putExtra("data", imageFileUri.toString());
setResult(-1, i);
finish();
}});
retry.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}});
}
public void insertImage(byte[] data)
{
Bitmap b = null;
try {
b = GeneralUtils.decodeFile(data, this);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 80, bos);
//b = null;
Bitmap bitmap = BitmapFactory.decodeByteArray(bos.toByteArray(), 0, bos.size());
Matrix m = new Matrix();
if (b.getWidth() > b.getHeight())
{
m.postRotate(90);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, true);
}
String result = MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "", "");
b.recycle();
data = null;
b = null;
m = null;
imageFileUri = Uri.parse(result);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
camera.takePicture(null, null, null, this);
}
}

Error in my logcat, after some refreshes on my list my app crashes

Posts.java
public class Posts extends Activity implements OnCheckedChangeListener {
private static final String TAG = "POSTS";
private static final int NULL_COUNTRY_CODE = 6;
private static final int POST_BACK_BTN = 7;
private static final int CHANGE = 8;
private String un;
private SimpleAdapter simpleAdpt;
private EditText post;
private RadioGroup radGrp;
private GPSTracker mGPS;
private PullToRefreshListView lv;
private String initial = "Se eida ";
private String code;
private String unm;
private String postui;
private String tmp;
private String idPost;
// The data to show
private List<Map<String, String>> postsList = new ArrayList<Map<String, String>>();
JSONArray array = null;
private static List<String> list = new ArrayList<String>();
private String pst;
private AlertDialogFragments adf;
private FragmentTransaction ft;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_posts);
initLocation();
if (code == null) {
ft = getFragmentManager().beginTransaction();
// Create and show the dialog.
adf = new AlertDialogFragments(NULL_COUNTRY_CODE);
adf.show(ft, "dialog");
}
init();
}
private HashMap<String, String> createPost(String key, String name) {
HashMap<String, String> post = new HashMap<String, String>();
post.put(key, name);
return post;
}
private void initLocation() {
mGPS = new GPSTracker(this);
final double mLat = mGPS.getLatitude();
final double mLong = mGPS.getLongitude();
getAddress(mLat, mLong);
}
private void getAddress(double mLat, double mLong) {
try {
Geocoder gcd = new Geocoder(this, Locale.getDefault());
List<Address> addresses = gcd.getFromLocation(mLat, mLong, 100);
if (addresses.size() > 0) {
addresses = gcd.getFromLocation(mLat, mLong, 1);
code = addresses.get(0).getCountryCode();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
private void init() {
this.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
Intent i = getIntent();
un = i.getStringExtra("un");
post = (EditText) findViewById(R.id.lbl_txt);
radGrp = (RadioGroup) findViewById(R.id.rdg);
radGrp.setOnCheckedChangeListener(this);
// We get the ListView component from the layout
lv = (PullToRefreshListView) findViewById(R.id.listView);
// Set a listener to be invoked when the list should be refreshed.
((PullToRefreshListView) lv)
.setOnRefreshListener(new OnRefreshListener() {
#Override
public void onRefresh() {
((PullToRefreshListView) lv)
.setLastUpdated(new SimpleDateFormat(
"dd-MM-yyyy HH:mm").format(new Date()));
new GetData().execute();
}
});
simpleAdpt = new CustomAdapter(this, postsList,
android.R.layout.simple_list_item_1, new String[] { "post" },
new int[] { android.R.id.text1 });
new GetData().execute();
}
public class CustomAdapter extends SimpleAdapter {
HashMap<String, String> map = new HashMap<String, String>();
public CustomAdapter(Context context,
List<? extends Map<String, String>> data, int resource,
String[] from, int[] to) {
super(context, data, resource, from, to);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = super.getView(position, convertView, parent);
if (row != null) {
if (position % 2 == 0)
row.setBackgroundResource(R.drawable.listview_selector_even);
else
row.setBackgroundResource(R.drawable.listview_selector_odd);
}
return row;
}
}
private class GetData extends AsyncTask<String, String, String> {
private ProgressDialog progDailog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progDailog = new ProgressDialog(Posts.this);
progDailog.setMessage("Loading...");
progDailog.setIndeterminate(false);
progDailog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progDailog.setCancelable(true);
progDailog.show();
}
#Override
protected String doInBackground(String... params) {
postsList.clear();
list.clear();
new Thread(new Runnable() {
public void run() {
//getting data from server and store into results
try {
array = new JSONArray(result);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < array.length(); i++) {
JSONObject row = null;
try {
row = array.getJSONObject(i);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
unm = row.getString("Username");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
postui = row.getString("Post");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
tmp = row.getString("Timestamp");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
idPost = row.getString("Id");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pst = unm + ":\n" + postui + "\n"
+ tmp.substring(0, tmp.length() - 2);
list.add(i, idPost);
postsList.add(createPost("post", pst));
}
runOnUiThread(new Runnable() {
#Override
public void run() {
lv.setSelector(R.drawable.row_pressed);
lv.setAdapter(simpleAdpt);
simpleAdpt.notifyDataSetChanged();
registerForContextMenu(lv);
}
});
}
}).start();
return null;
}
#Override
protected void onPostExecute(String unused) {
super.onPostExecute(unused);
simpleAdpt.notifyDataSetChanged();
progDailog.dismiss();
((PullToRefreshListView) lv).onRefreshComplete();
}
}
// We want to create a context Menu when the user long click on an item
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterContextMenuInfo aInfo = (AdapterContextMenuInfo) menuInfo;
// We know that each row in the adapter is a Map
HashMap<?, ?> map = (HashMap<?, ?>) simpleAdpt
.getItem(aInfo.position - 1);
String string = (String) map.get("post");
menu.setHeaderTitle("Options");
menu.add(1, 1, 1, "Share via:");
menu.add(1, 2, 2, "Copy");
menu.add(1, 3, 3, "Delete");
menu.add(1, 1, 1, "Share via:");
menu.add(1, 2, 2, "Copy");
}
// This method is called when user selects an Item in the Context menu
#SuppressWarnings("deprecation")
#Override
public boolean onContextItemSelected(MenuItem item) {
int itemId = item.getItemId();
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
switch (itemId) {
case 1:
// Share intent
String key = ((TextView) info.targetView).getText().toString();
// create the send intent
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
// set the type
shareIntent.setType("text/plain");
// add a subject
shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
R.string.app_name);
// build the body of the message to be shared
String shareMessage = key.substring(0, key.length() - 20)
.substring(key.indexOf(":") + 2);
// add the message
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT,
shareMessage);
// start the chooser for sharing
startActivity(Intent.createChooser(shareIntent, "Share via: "));
break;
case 2:
// Copy
String key1 = ((TextView) info.targetView).getText().toString();
int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText(key1.substring(0, key1.length() - 20)
.substring(key1.indexOf(":") + 2));
Toast.makeText(this, "Post copied.", Toast.LENGTH_SHORT).show();
} else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData
.newPlainText("", key1.substring(0, key1.length() - 20)
.substring(key1.indexOf(":") + 2));
clipboard.setPrimaryClip(clip);
Toast.makeText(this, "Post copied.", Toast.LENGTH_SHORT).show();
}
break;
case 3:
// Delete
int index = info.position - 1;
//deletes a post
deletePost(list.get(index), this);
new GetData().execute();
break;
}
return true;
}
My Logcat output
The content of the adapter has changed but ListView did not receive a
notification. Make sure the content of your adapter is not modified
from a background thread, but only from the UI thread.
You are using postList as content for your adapter. Then you change that content in doInBackground(). You cannot do that.
Here's what you have to do. Gather the data in doInBackground() and return it. The result will be passed to onPostExecute. Then, in onPostExecute, change the adapter content and notify about the data change. onPostExecute() runs in the UI thread.
If you want to periodically update your AdapterView, use publishProgress.
You don't need to start a new Thread in doInBackground and you don't need to invoke any runOnUIThread method. It will work (especially the runOnUIThread part) but then you don't need the AsyncTask class.

Categories