i have 2 Activitys. In the first Updater Activity i want to create a ProgressDialog,
which I want to show in the other Activity(TopRatedFragment). How can i do this?
public class Updater extends Activity {
String pid = "1";
JSONObject x;
int success;
ProgressDialog pDialog;
int y;
private String result;
String Url = "domain.com";
JSONArray products = null;
private static final String TAG_SUCCESS = "success";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.checker);
}
public int getResult(JSONObject json) {
try {
Log.d("Request: ", json.toString());
// Getting JSON Array
success = json.getInt(TAG_SUCCESS);
Log.i("Status 2 z", "Status z: "+ success);
} catch (JSONException e) {
e.printStackTrace();
}
return success;
}
public final int updaten(String site) {
Update task = new Update();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", site));
x = task.execute(params).get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
y = getResult(x);
return y;
}
class Update extends AsyncTask<List<NameValuePair>, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(Updater.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected JSONObject doInBackground(List<NameValuePair>... params) {
// Getting JSON from URL
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(Url, params[0]);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
Log.d("Updater ", json.toString());
}
}
public class TopRatedFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_top_rated, container, false);
return rootView;
}
This method is called after an OnClickListener.
public void Updatequest(final String site) {
ConnectivityManager connMgr = (ConnectivityManager) getActivity()
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
ado = new Updater();
Log.i("Status 2 z", "Status z: " + z);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
getActivity());
// set title
alertDialogBuilder.setTitle("Do you really want to report?");
// set dialog message
alertDialogBuilder
.setMessage("Press Yes to submit your report")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// if this button is clicked, close
// current activity
int z = ado.updaten(site); //call the method in the other Activity
Log.i("Status 1 z", "Status z: " + z);
if (z == 1) {
Toast.makeText(
getActivity(),
"Thanks, your report was successfull",
Toast.LENGTH_LONG).show();
z = 0;
} else {
Toast.makeText(
getActivity(),
"Please check your Internet connection!",
Toast.LENGTH_LONG).show();
}
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
else {
Toast.makeText(getActivity(),
"An error has occured please check your Internet Connection again", Toast.LENGTH_LONG)
.show();
}
If i click on the Button, a lot of errors are shown. The first is the FATAL EXCEPTION: main
and a java.lang.NullPointerException.
How can I fix that ?
If you look into the logcat, you will find the full exception backtrace. It tells you the line, where the NullPointerException was thrown. Please check, if that button really exists. Maybe, it is caused by a wrong ID or something else.
If you have a very loooong backtrace, read through the trace and look for "Caused by...." lines. It often happened to me, that the exception was encapsulated and wasn't obvious shown in the logcat.
Related
I have a register activity in my application. This has inputs of userid,email,password and mobile no. I have created an UI.
code:
public class RegisterActivity extends AppCompatActivity {
TextView already;
Button signUp;
RelativeLayout parent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
parent = (RelativeLayout)findViewById(R.id.parentPanel);
setupUI(parent);
already = (TextView)findViewById(R.id.alreadyRegistered);
signUp = (Button) findViewById(R.id.sign_up_button);
already.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(RegisterActivity.this,LoginActivity.class));
}
});
signUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(RegisterActivity.this,LoginActivity.class));
}
});
}
public static void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
public void setupUI(View view) {
//Set up touch listener for non-text box views to hide keyboard.
if(!(view instanceof EditText)) {
view.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
hideSoftKeyboard(RegisterActivity.this);
return false;
}
});
}
//If a layout container, iterate over children and seed recursion.
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
View innerView = ((ViewGroup) view).getChildAt(i);
setupUI(innerView);
}
}
}
}
Now I want to sync this UI with server.
For this I have a code of asyncTask created in another activity. How can I call this code or implement this code with UI?
AsyncTask code : RegisterActivity
public class RegisterActivity extends AppCompatActivity {
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
context = this;
RegisterAsyncTask task = new RegisterAsyncTask();
String userPhoto = "iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlwSFlLBAIHAGdIMrN7hH1jKkmZz+d7MPu15md6PtCyrHmqvsgNVjY7Djh69OgwEaU1pkVwanKK0NLSsgvA8Vk=";
HashMap<String, String> params = new HashMap<String, String>();
params.put("userUsername", "user1");
params.put("userPassword", "user1");
params.put("gender", "M");
params.put("birthDate", "1986/7/12");
params.put("religion", "Hindu");
params.put("nationality", "Indian");
params.put("motherTongue", "Marathi");
params.put("birthPlace", "Pune");
params.put("userCountry", "India");
params.put("userState", "Maharashtra");
params.put("userCity", "Nashik");
params.put("userPincode", "422101");
params.put("userEmailid", "user1#gmail.com");
params.put("userMobileNo", "9696323252");
params.put("userPhoto", userPhoto);
}
public class RegisterAsyncTask extends AsyncTask<Map<String, String>, Void, JSONObject>{
#Override
protected JSONObject doInBackground(Map<String, String>... params) {
try {
String api = context.getResources().getString(R.string.server_url) + "api/user/register.php";
Map2JSON mjs = new Map2JSON();
JSONObject jsonParams = mjs.getJSON(params[0]);
ServerRequest request = new ServerRequest(api, jsonParams);
return request.sendRequest();
} catch(JSONException je) {
return Excpetion2JSON.getJSON(je);
}
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
Log.d("ServerResponse", jsonObject.toString());
try {
int result = jsonObject.getInt("result");
String message = jsonObject.getString("message");
if ( result == 1 ) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
//Code for having successful result for register api goes here
} else {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
//Code when api fails goes here
}
} catch(JSONException je) {
je.printStackTrace();
Toast.makeText(context, je.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}
How can I sync this? Please help. Thank you.
EDIT:
getEventsAsyncTask:
public class GetEventsAsyncTask extends AsyncTask<Void, Void, JSONObject> {
String api;
private Context context;
public GetEventsAsyncTask(Context context) {
this.context = context;
}
#Override
protected JSONObject doInBackground(Void... params) {
try {
api = context.getResources().getString(R.string.server_url) + "api/event/getEvents.php";
ServerRequest request = new ServerRequest(api);
return request.sendGetRequest();
} catch(Exception e) {
return Excpetion2JSON.getJSON(e);
}
} //end of doInBackground
#Override
protected void onPostExecute(JSONObject response) {
super.onPostExecute(response);
Log.e("ServerResponse", response.toString());
try {
int result = response.getInt("result");
String message = response.getString("message");
if (result == 1 ) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
//code after getting profile details goes here
} else {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
//code after failed getting profile details goes here
}
} catch(JSONException je) {
je.printStackTrace();
Toast.makeText(context, je.getMessage(), Toast.LENGTH_LONG).show();
}
} //end of onPostExecute
}
dialog :
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
String[] listContent = {"Wedding",
"Anniversary",
"Naming Ceremony/Baptism",
"Thread Ceremony",
"Engagement",
"Birthday",
"Friends and Family Meet",
"Funeral",
"Movie",
"Play"};
switch(id) {
case CUSTOM_DIALOG_ID:
dialog = new Dialog(PlanEventActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.choose_event_dialog);
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
dialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
#Override
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
}});
dialog.setOnDismissListener(new DialogInterface.OnDismissListener(){
#Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
}});
//Prepare ListView in dialog
dialog_ListView = (ListView)dialog.findViewById(R.id.dialoglist);
ArrayAdapter<String> adapter
= new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listContent);
dialog_ListView.setAdapter(adapter);
dialog_ListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
chooseEventText.setText(parent.getItemAtPosition(position).toString());
dismissDialog(CUSTOM_DIALOG_ID);
}});
break;
}
return dialog;
}
In this dialog want to show events from asyncTask. Thank you.
Not sure if i understand your question correctly, but to execute the AsyncTask, you just have to create an instance of RegisterAsyncTask and call the execute() method on it.
RegisterAsyncTask task = new RegisterAsyncTask();
task.execute(yourMap);
// you can pass multiple params to the execute() method
Or, if you don't need to get ahold of the instance:
new RegisterAsyncTask().execute(yourMap);
You can simply put your hashmap object, alongwith AsyncTask in your login activity code, and simply call AsyncTask in following manner.
HashMap<String, String> params = new HashMap<String, String>();
params.put("userUsername", "user1");
params.put("userPassword", "user1");
params.put("gender", "M");
params.put("birthDate", "1986/7/12");
params.put("religion", "Hindu");
params.put("nationality", "Indian");
params.put("motherTongue", "Marathi");
params.put("birthPlace", "Pune");
params.put("userCountry", "India");
params.put("userState", "Maharashtra");
params.put("userCity", "Nashik");
params.put("userPincode", "422101");
params.put("userEmailid", "user1#gmail.com");
params.put("userMobileNo", "9696323252");
params.put("userPhoto", userPhoto);
//call asynctask like this.
RegisterAsyncTask task = new RegisterAsyncTask();
task.execute(params);
I have an asynTask to get all the events from server. This data from asyncTask I want to show as a list in a dialog. How can I do this?
getEventsAsyncTask
public class GetEventsAsyncTask extends AsyncTask<Void, Void, JSONObject> {
String api;
private Context context;
public GetEventsAsyncTask(Context context) {
this.context = context;
}
#Override
protected JSONObject doInBackground(Void... params) {
try {
api = context.getResources().getString(R.string.server_url) + "api/event/getEvents.php";
ServerRequest request = new ServerRequest(api);
return request.sendGetRequest();
} catch(Exception e) {
return Excpetion2JSON.getJSON(e);
}
} //end of doInBackground
#Override
protected void onPostExecute(JSONObject response) {
super.onPostExecute(response);
Log.e("ServerResponse", response.toString());
try {
int result = response.getInt("result");
String message = response.getString("message");
if (result == 1 ) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
//code after getting profile details goes here
} else {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
//code after failed getting profile details goes here
}
} catch(JSONException je) {
je.printStackTrace();
Toast.makeText(context, je.getMessage(), Toast.LENGTH_LONG).show();
}
} //end of onPostExecute
}
dialog:
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
String[] listContent = {"Wedding",
"Anniversary",
"Naming Ceremony/Baptism",
"Thread Ceremony",
"Engagement",
"Birthday",
"Friends and Family Meet",
"Funeral",
"Movie",
"Play"};
switch(id) {
case CUSTOM_DIALOG_ID:
dialog = new Dialog(PlanEventActivity.this);
// dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.choose_event_dialog);
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
dialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
#Override
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
// Toast.makeText(PlanEventActivity.this,
// "OnCancelListener",
// Toast.LENGTH_LONG).show();
}});
dialog.setOnDismissListener(new DialogInterface.OnDismissListener(){
#Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
// Toast.makeText(PlanEventActivity.this,
// "OnDismissListener",
// Toast.LENGTH_LONG).show();
}});
//Prepare ListView in dialog
dialog_ListView = (ListView)dialog.findViewById(R.id.dialoglist);
ArrayAdapter<String> adapter
= new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listContent);
dialog_ListView.setAdapter(adapter);
dialog_ListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
// Toast.makeText(PlanEventActivity.this,
// parent.getItemAtPosition(position).toString() + " clicked",
// Toast.LENGTH_LONG).show();
chooseEventText.setText(parent.getItemAtPosition(position).toString());
dismissDialog(CUSTOM_DIALOG_ID);
}});
break;
}
return dialog;
}
In this dialog the list I am showing as a string. How can I show list of data from asyncTask? Thank you..
I created an android application. In this application I use the push notification concept. The notification is sent and received properly on the receiver.
Now I want to display the notification on status bar only for 20 second after that it will disappear. Can anyone tell me how can I do this? This is what I´ve so far.
public class ViewRecievedJobs extends Activity {
//private Button accept,reject;
private SharedPreferences pref;
private String login_token;
int status;
FragmentSendJob fsj;
ListView list;
Context con;
int pos;
static String job_id;
DatabaseAdmin database ;
ArrayList<HashMap<String, String>> adsArray = new ArrayList<HashMap<String,String>>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.view_received_jobs);
con=this;
pref=this.getSharedPreferences("Driver", MODE_WORLD_READABLE);
login_token = pref.getString("login_token","login_token");
database = new DatabaseAdmin(getApplicationContext());
//adsArray = database.getRecords_ads("Select * from SUN_NOTI where received =0");
//
//fsj.job_id=id;
//Log.e("adsArray", ""+adsArray);
list=(ListView)findViewById(R.id.listView1);
}
#Override
protected void onResume()
{
// Log.e("onResume", "onResume");
adsArray.clear();
adsArray = database.getRecords_ads("Select * from SUN_NOTI where status = 1");
list.setAdapter(new ReceivedJobList());
super.onResume();
}
class ReceivedJobList extends BaseAdapter
{
public int getCount() {
// TODO Auto-generated method stub
return adsArray.size();
}
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return adsArray.get(arg0);
}
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
public View getView(final int arg0, View cView, ViewGroup arg2)
{
pos=arg0;
LayoutInflater inflater =(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
cView = inflater.inflate(R.layout.job_received, null);
TextView name = (TextView)cView.findViewById(R.id.esuburb);
TextView dest = (TextView)cView.findViewById(R.id.edestination);
name.setText(adsArray.get(arg0).get("suburb"));
dest.setText(adsArray.get(arg0).get("destination"));
// Button view = (Button) cView.findViewById(R.id.view);
Button accept = (Button) cView.findViewById(R.id.accept);
Button reject = (Button) cView.findViewById(R.id.reject);
accept.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
status=0;
job_id=adsArray.get(arg0).get("message_id");
new JobStatus().execute();
// new ViewAdvertisement().execute();
// Toast.makeText(LoginScreen.this, "You clicked the button", Toast.LENGTH_SHORT).show();
}
});
/* view.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent i =new Intent(con,Job_Detail.class);
i.putExtra("pos", ""+pos);
i.putExtra("from", "view");
i.putExtra("array",adsArray );
startActivity(i);
}
});*/
reject.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
status=2;
new JobStatus().execute();
}
});
return cView;
}
}
private class JobStatus extends AsyncTask<String, String, String[]> {
private ProgressDialog dialog;
protected void onPreExecute()
{
dialog = ProgressDialog.show(ViewRecievedJobs.this, "", "");
dialog.setContentView(R.layout.main);
dialog.show();
}
#Override
protected String[] doInBackground(final String... params)
{
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected())
{
HttpClient httpclient = new DefaultHttpClient();
JSONObject job1= new JSONObject();
try
{
job1.put("status_key",status);
job1.put("method", "job_status");
job1.put("login_token", login_token);
//job1.put("status",status);
job1.put("job_id",job_id);
StringEntity se = new StringEntity(job1.toString());
HttpPost httppost = new HttpPost("http://suntechwebsolutions.com/clients/DGCapp/webservice.php");
httppost.setEntity(se);
HttpResponse response1 = httpclient.execute(httppost);
String data1 = EntityUtils.toString(response1.getEntity());
Log.e("response",""+data1);
JSONObject jo = new JSONObject(data1);
String err=jo.getString("err-code");
if(err.equals("0"))
{
if( status == 0)
{
database.update_data(adsArray.get(pos).get("message_id"),"2");
//Toast.makeText(con, "Job Accepted", Toast.LENGTH_SHORT).show();
//show_Toast("Job Accepted");
dialog.dismiss();
Intent i =new Intent(con,Job_Detail.class);
i.putExtra("pos", ""+pos);
i.putExtra("from", "accept");
i.putExtra("array",adsArray );
startActivity(i);
}
else
{
database.delete_data(adsArray.get(pos).get("message_id"));
//show_Toast("Job Rejected");
//Toast.makeText(con, "Job Rejected", Toast.LENGTH_SHORT).show();
adsArray.clear();
adsArray = database.getRecords_ads("Select * from SUN_NOTI where status = 1");
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
final AlertDialog.Builder alert = new AlertDialog.Builder(ViewRecievedJobs.this);
alert.setTitle("Alert !");
alert.setMessage("No Internet connection ");
alert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog2,
int whichButton)
{
dialog.dismiss();
dialog2.dismiss();
}
});
runOnUiThread(new Runnable()
{
public void run()
{
//pDialog.dismiss();
alert.show();
}
});
}
return params;
}
#SuppressLint("NewApi")
#Override
protected void onPostExecute(String[] result)
{
super.onPostExecute(result);
if(dialog.isShowing())
{
dialog.dismiss();
}
if(status == 2)
{
Toast.makeText(con, "Job Rejected", Toast.LENGTH_SHORT).show();
list.setAdapter(new ReceivedJobList());
}
}
/*public void show_Toast(String msg)
{
Toast.makeText(con, msg, Toast.LENGTH_SHORT).show();
}*/
}
}
you can create a service that runs in the background and that will timeout after 20 minutes and delete your notification.Before that a notification should be there to notify the user... and the user should be able to dismiss it on their own.
Reference :
Make notification disappear after 5 minutes
I'm currently working on an android app with web services, using an external database. The app consists of several tasks and each task is assigned to each camera id. Each camera have specific long/lat stored in the database. So right now when I select a specific task, there would be a guide button showing the user current location as a marker in the google map. I want to display the long/lat of the task as a marker on the google map, so there would be 2 marker. Just need some help with the android coding. Any help would be appreciated!
GoogleMapActivity.java
public class GoogleMapActivity extends Activity implements LocationListener {
GoogleMap map;
private String cameraid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_google_map);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
}
#Override
public void onLocationChanged(Location location) {
map.clear();
MarkerOptions mp = new MarkerOptions();
mp.position(new LatLng(location.getLatitude(), location.getLongitude()));
mp.title("My Current Location");
map.addMarker(mp);
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 16));
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
AcceptTask.java
public class AcceptTask extends SherlockActivity {
private static String sendingURL,
url,
imageURL,
dateTimeP,
notificationID,
cameraID;
private String check = null;
// JSON Node names
private static final String TAG_GET = "jobViewResult",
TAG_IMAGEURL = "imageurl",
TAG_MESSAGE = "vmessage",
TAG_GETA = "assignResult",
TAG_STATUS = "assignStatus";
private ProgressDialog pDialog;
public static final int progress_bar_type = 0;
private TextView tvCamera, tvDate;
private ImageView my_image;
// contacts JSONObject
JSONObject api = null;
private long userInteractionTime = 0;
AsyncTask<Void, Void, Void> mRegisterTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_accept_task);
tvCamera = (TextView) findViewById(R.id.tv_CameraID);
tvDate = (TextView) findViewById(R.id.tv_DateR);
my_image = (ImageView) findViewById(R.id.img_Task);
//set the icon clickable
getSupportActionBar().setHomeButtonEnabled(true);
//add an < arrow on the icon
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
File file = new File("/sdcard/LocationSystem/pendingtask_temp.jpg" );
if (file.exists()) {
file.delete();
}
if(isNetworkConnected()){
try{
// getting intent data
Intent intent = getIntent();
/** Get values from previous intent */
dateTimeP = intent.getStringExtra("TAG_IMAGE_TIME_DATE_P");
cameraID = intent.getStringExtra("TAG_CAMERA_ID_P");
notificationID = intent.getStringExtra("TAG_NOTIFICATION_ID");
/** Display cameraID and date time */
tvCamera.setText(cameraID);
tvDate.setText(dateTimeP);
url = "url";
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
api = json.getJSONObject(TAG_GET);
check = api.getString(TAG_MESSAGE);
// Storing each json item in variable
imageURL = api.getString(TAG_IMAGEURL);
} catch (JSONException e) {
e.printStackTrace();
}
if(check.equals("Job available")){
new DownloadImageTask().execute(imageURL);
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AlertDialogTheme));
builder.setCancelable(false);
builder.setTitle("Job Unavailable");
builder.setMessage(check);
// Setting Icon to Dialog
builder.setIcon(R.drawable.ic_action_error);
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent loadIntent = new Intent();
loadIntent.putExtra("startUpdate_PList", "start");
setResult(Activity.RESULT_OK, loadIntent);
finish();
}
});
builder.show();
}
} catch(Exception e) {
if(e != null) {
showServerErrorDialog();
}
}
}else{showNetworkErrorDialog();}
}
private void showServerErrorDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AlertDialogTheme));
builder.setCancelable(false);
builder.setTitle("Server Error");
builder.setMessage("Server is currently unable to connect. Please check your network connectivity.");
// Setting Icon to Dialog
builder.setIcon(R.drawable.ic_action_error);
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.show();
}
private void showNetworkErrorDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AlertDialogTheme));
builder.setTitle("No Network Connection");
builder.setMessage("Please turn on your mobile 3G or connect to a network in order to use this application.");
// Setting Icon to Dialog
builder.setIcon(R.drawable.ic_action_error);
builder.setPositiveButton("Close",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
AcceptTask.this.finish();
}
});
builder.setNegativeButton("Setting",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//calling setting menu
startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);
}
});
builder.show();
}
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null) {
return false;
} else{
return true;
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case android.R.id.home:
if(my_image.getDrawable() != null){
File file = new File("/sdcard/LocationSystem/pendingtask_temp.jpg" );
if (file.exists()) {
file.delete();
}
}
Intent loadIntent = new Intent();
loadIntent.putExtra("startUpdate_PList", "start");
setResult(Activity.RESULT_OK, loadIntent);
finish();
break;
default:
return super.onOptionsItemSelected(item);
}
return false;
}
#Override
public void onUserInteraction() {
userInteractionTime = System.currentTimeMillis();
super.onUserInteraction();
Log.i("appname","Interaction");
}
#Override
public void onUserLeaveHint() {
long uiDelta = (System.currentTimeMillis() - userInteractionTime);
super.onUserLeaveHint();
if (uiDelta < 100){
Logout();
}
}
#Override
public void onResume() {
super.onResume();
if(isNetworkConnected()){
try{
SharedPreferences checkLogin1 = getApplicationContext().getSharedPreferences( "checklogin", 0);
String staffID = checkLogin1.getString("staffID", "");
String staffPassword = checkLogin1.getString("password", "");
DefaultHttpClient httpClient = new DefaultHttpClient();
//get the unique id
SharedPreferences pref = getApplicationContext().getSharedPreferences( "checklogin", 0);
String checkID = pref.getString("loginRID", "");
HttpGet request = new HttpGet(url);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(request);
HttpEntity responseEntity = response.getEntity();
// Read response data into buffer
char[] buffer = new char[(int) responseEntity
.getContentLength()];
InputStream stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
reader.read(buffer);
stream.close();
JSONObject svr = new JSONObject(new String(buffer));
JSONObject obj = svr.getJSONObject("loginTestResult");
String validation = obj.getString("valid");
String position = obj.getString("position");
String companyID = obj.getString("companyID");
String messageStatus = obj.getString("message");
if(validation.equals("1")){
checkNotNull(SERVER_URL, "SERVER_URL");
checkNotNull(SENDER_ID, "SENDER_ID");
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(this);
// Make sure the manifest was properly set - comment out this line
// while developing the app, then uncomment it when it's ready.
GCMRegistrar.checkManifest(this);
//mDisplay = (TextView) findViewById(R.id.display);
//gcmIDtxt =(TextView) findViewById(R.id.gcmID);
registerReceiver(mHandleMessageReceiver, new IntentFilter(DISPLAY_MESSAGE_ACTION));
final String regId = GCMRegistrar.getRegistrationId(this);
System.out.print(regId);
if (regId.equals("")) {
// Automatically registers application on startup.
GCMRegistrar.register(this, SENDER_ID);
} else {
// Device is already registered on GCM, check server.
// if (GCMRegistrar.isRegisteredOnServer(this)) {
// // Skips registration.
// //mDisplay.append(getString(R.string.already_registered) + "\n");
// //gcmIDtxt.setText(regId);
//
// } 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 context = this;
mRegisterTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
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) {
mRegisterTask = null;
}
};
mRegisterTask.execute(null, null, null);
// }
}
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AlertDialogTheme));
builder.setCancelable(false);
builder.setTitle("Error");
builder.setMessage(messageStatus + " Please sign in again.");
// Setting Icon to Dialog
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SharedPreferences pref2 = getApplicationContext().getSharedPreferences("checklogin", 0);
final SharedPreferences.Editor editor1 = pref2.edit();
editor1.putInt("login", 0);
editor1.commit();
Intent intent = new Intent(AcceptTask.this, LoginPage.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
});
builder.show();
}
} catch(Exception e) {
if(e != null) {
showServerErrorDialog();
}
}
}else{
showNetworkErrorDialog();
}
//runAcceptedTask();
}
private final BroadcastReceiver mHandleMessageReceiver =
new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
//mDisplay.append(newMessage + "\n");
}
};
private void checkNotNull(Object reference, String name) {
if (reference == null) {
throw new NullPointerException(
getString(R.string.error_config, name));
}
}
private void Logout(){
if(isNetworkConnected()){
try{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
DefaultHttpClient httpClient = new DefaultHttpClient();
//get the unique id
SharedPreferences pref = getApplicationContext().getSharedPreferences( "checklogin", 0);
String checkID = pref.getString("loginRID", "");
String staffID = pref.getString("staffID", "");
HttpGet request = new HttpGet(url);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(request);
HttpEntity responseEntity = response.getEntity();
// Read response data into buffer
char[] buffer = new char[(int) responseEntity
.getContentLength()];
InputStream stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
reader.read(buffer);
stream.close();
JSONObject svr = new JSONObject(new String(buffer));
JSONObject obj = svr.getJSONObject("logoutResult");
String messageStatus = obj.getString("userMessage");
if(messageStatus.equals("Updated Successfully!!")){
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AlertDialogTheme));
builder.setCancelable(false);
builder.setTitle("Error");
builder.setMessage(messageStatus);
// Setting Icon to Dialog
builder.setIcon(R.drawable.ic_action_error);
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.show();
}
} catch (Exception e) {
if(e != null) {
showServerErrorDialog();
}
}
}
else{
showNetworkErrorDialog();
}
}
//accept task button
public void acceptTask(View v) {
File file = new File("/sdcard/LocationSystem/pendingtask_temp.jpg" );
if (file.exists()) {
file.delete();
}
AlertDialog.Builder builder = new AlertDialog.Builder(AcceptTask.this);
builder.setTitle("Confirm Accept");
builder.setMessage("Are you sure to accept this job?");
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if(isNetworkConnected()){
try{
// Do do my action here
SharedPreferences pref = getApplicationContext().getSharedPreferences(
"checklogin", 0);
String staffID = pref.getString("staffID", "");
//sendingURL = ""+staffID;
sendingURL = "url";
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(sendingURL);
try {
api = json.getJSONObject(TAG_GETA);
check = api.getString(TAG_STATUS);
} catch (JSONException e) {
if(e != null) {
showServerErrorDialog();}
}
if(check.equals("Job available")){
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(sendingURL);
try {
HttpResponse response = httpclient.execute(httpget);
Toast.makeText(getApplicationContext(), "You accepted the job.", Toast.LENGTH_SHORT).show();
Intent loadIntent = new Intent();
loadIntent.putExtra("startUpdate_PList", "start");
setResult(Activity.RESULT_OK, loadIntent);
finish();
}
catch (IOException e) {
if(e != null) {
showServerErrorDialog();}
}
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(AcceptTask.this, R.style.AlertDialogTheme));
builder.setCancelable(false);
builder.setTitle("Job Unavailable");
builder.setMessage(check);
// Setting Icon to Dialog
builder.setIcon(R.drawable.ic_action_error);
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent loadIntent = new Intent();
loadIntent.putExtra("startUpdate_PList", "start");
setResult(Activity.RESULT_OK, loadIntent);
finish();
}
});
builder.show();
}
} catch(Exception e) {
if(e != null) {
showServerErrorDialog();
}
}
}else{
showNetworkErrorDialog();
}
}
});
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
private class DownloadImageTask extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
protected String doInBackground(String... urls) {
int count;
try {
URL url = new URL(urls[0]);
URLConnection connection = url.openConnection();
connection.connect();
int lenghtOfFile = connection.getContentLength();
InputStream in = new BufferedInputStream(url.openStream(), 8192);
byte data[] = new byte[1024];
// Output stream to write file
OutputStream output = new FileOutputStream("/sdcard/LocationSystem/pendingtask_temp.jpg");
long total = 0;
while((count = in.read(data)) != -1){
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
File file = new File(getExternalCacheDir(), "pendingtask_temp.jpg" );
if (file.exists()) {
file.delete();
}else{
output.write(data, 0, count);
}
}
output.flush();
output.close();
in.close();
} catch (Exception e) {
Log.e("Error", e.getMessage());
if(e != null) {
showServerErrorDialog();
}
}
return null;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);
String imagePath = Environment.getExternalStorageDirectory().toString() + "/LocationSystem/pendingtask_temp.jpg";
// setting downloaded into image view
my_image.setImageDrawable(Drawable.createFromPath(imagePath));
File file = new File("/sdcard/LocationSystem/pendingtask_temp.jpg" );
if (file.exists()) {
file.delete();
}
if (my_image.getDrawable() == null){
Toast.makeText(AcceptTask.this, "Please select again!",Toast.LENGTH_LONG).show();
finish();
}
}
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type: // we set this to 0
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
//pDialog.setButton("Cancel", (DialogInterface.OnClickListener) null);
pDialog.setButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
AcceptTask.this.finish();
}
});
pDialog.setCancelable(false);
pDialog.show();
return pDialog;
default:
return null;
}
}
#Override
public void onBackPressed() {
if(my_image.getDrawable() != null){
File file = new File("/sdcard/LocationSystem/pendingtask_temp.jpg" );
if (file.exists()) {
file.delete();
}
}
Intent loadIntent = new Intent();
loadIntent.putExtra("startUpdate_PList", "start");
setResult(Activity.RESULT_OK, loadIntent);
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.accept_task, menu);
return true;
}
}
You can do an asynck task to get the DB values and call this task in onlocationchange.
Actually i am parsing in json id,content,title,count.But i dont want to display id,but after click the button it has to get the id value and i have to send that id to the server side.
this is my json parsing values:
{"post":[{"id":170,"title":"Exams","content":"pass","count":3},{"id":169,"title":"Exams","content":"pass","count":3}, From here i want to get the id after click the pray button and want to send that id in post method also.
Activity.java
public class MainActivity extends Activity implements FetchDataListener,OnClickListener
{
private static final int ACTIVITY_CREATE=0;
private ProgressDialog dialog;
ListView lv;
private List<Application> items;
private Button btnGetSelected;
private Button praycount;
public int count;
private String stringVal;
private TextView value;
//private ProjectsDbAdapter mDbHelper;
//private SimpleCursorAdapter dataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_item);
//mDbHelper = new ProjectsDbAdapter(this);
//mDbHelper.open();
//fillData();
//registerForContextMenu(getListView());
praycount = (Button) findViewById(R.id.pray);
praycount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count++;
stringVal = Integer.toString(count);
value.setText(stringVal);
if(value.getText().toString().length()<1){
// out of range
//Toast.makeText(this, "please enter something", Toast.LENGTH_LONG).show();
}else{
praydata(stringVal);
}
}});
lv =(ListView)findViewById(R.id.list);
btnGetSelected = (Button) findViewById(R.id.btnget);
btnGetSelected.setOnClickListener(this);
initView();
}
public void praydata(String valueIWantToSend) {
// Create a new HttpClient and Post Header.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.ginfy.com/api/v1/posts/id.json");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("post[id]", valueIWantToSend));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//httppost.addHeader("Authorization","Basic "+authorization);
//httppost.addHeader("Content-Type","application/x-www-form-urlencoded");
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
httppost.setHeader("Accept", "application/json");
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
private void initView()
{
// show progress dialog
dialog = ProgressDialog.show(this, "", "Loading...");
String url = "http://www.ginfy.com/api/v1/posts.json";
FetchDataTask task = new FetchDataTask(this);
task.execute(url);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
createProject();
return super.onMenuItemSelected(featureId, item);
}
private void createProject() {
Intent i = new Intent(this, AddPrayerActivity.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
initView();
}
#Override
public void onFetchComplete(List<Application> data)
{
this.items = data;
// dismiss the progress dialog
if ( dialog != null )
dialog.dismiss();
// create new adapter
ApplicationAdapter adapter = new ApplicationAdapter(this, data);
// set the adapter to list
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
CheckBox chk = (CheckBox) view.findViewById(R.id.checkbox);
Application bean = items.get(position);
if (bean.isSelected()) {
bean.setSelected(false);
chk.setChecked(false);
} else {
bean.setSelected(true);
chk.setChecked(true);
}
}
});
}
// Toast is here...
private void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
#Override
public void onFetchFailure(String msg)
{
// dismiss the progress dialog
if ( dialog != null )
dialog.dismiss();
// show failure message
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
#Override
public void onClick(View v) {
StringBuffer sb = new StringBuffer();
// Retrive Data from list
for (Application bean : items) {
if (bean.isSelected()) {
sb.append("Title:");
sb.append(Html.fromHtml(bean.getTitle()));
sb.append(",Content:");
sb.append(Html.fromHtml(bean.getContent()));
sb.append("\n");
}
}
showAlertView(sb.toString().trim());
}
#SuppressWarnings("deprecation")
private void showAlertView(String str) {
AlertDialog alert = new AlertDialog.Builder(this).create();
final String strContactList = str.substring(0, str.length());
if (TextUtils.isEmpty(str)) {
alert.setTitle("Not Selected");
alert.setMessage("No One is Seleceted!!!");
} else {
// Remove , end of the name
alert.setTitle("Selected");
alert.setMessage(strContactList);
}
alert.setButton("sms", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//sendSMS();
/*Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", strContactList);
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);
finish();*/
Intent intent1=new Intent(MainActivity.this,SendSMSActivity.class);
//Log.d("test","strContactList: "+strContactList);
intent1.putExtra("firstKeyName", strContactList);
startActivity(intent1);
}
});
Actually want i want that i want to get an id fronm one json its already i mention,after click the button selection id i want to send again in another json url as post method.
for this you can use javascript to read the id of the particular property selected and using that you can display what ever details you want.