Android Java progressdialog from Baseadapter - java

On my android app, I have my own BaseAdapter, in this I have a click button listener with the following code:
btnShareFacebook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
videoMoreLayout.setVisibility(View.GONE);
final String id = videoIDs[position];
videoActions = new VideoActions();
hfu = new HttpFileUpload(videoPathURL[position], token);
final ProgressDialog pDialog = new ProgressDialog(activity);
pDialog.setMessage("Preparing video to share...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
if (!isOnline()) {
Toast.makeText(activity,
activity.getString(R.string.noInternetConnection),
Toast.LENGTH_SHORT).show();
} else {
try {
String arr[] = videoPathURL[position].split("/upload/videos/");
final String finalVideoName = (arr[arr.length-1]);
File DoutFile = new File(
Environment.getExternalStorageDirectory() +
File.separator + "vidytape_shared" + File.separator + finalVideoName);
if(!DoutFile.exists()){
pDialog.show();
String downloadResult = videoActions.downloadToShare(token, activity, id, videoPathURL[position], finalVideoName);
if (downloadResult.equalsIgnoreCase("POST_FAILURE") || downloadResult.equalsIgnoreCase("FAILURE_102")) {
Toast.makeText(
activity,
activity.getString(R.string.someErrorOccurred),
Toast.LENGTH_SHORT).show();
}
/*if(hfu.Download_File_To_Share(finalVideoName, videoPathURL[position])){
Toast.makeText(activity, "OK", Toast.LENGTH_LONG).show();
//pDialog.dismiss();
} else {
Toast.makeText(activity, "ERRO", Toast.LENGTH_LONG).show();
}*/
}
pDialog.dismiss();
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("video/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(DoutFile));
share.putExtra(Intent.EXTRA_TEXT,
"" + activity.getResources().getString(R.string.app_name));
share.setPackage("com.facebook.katana");
activity.startActivity(share);
} catch (Exception e) {
pDialog.dismiss();
Toast.makeText(
activity,
activity.getString(R.string.facebookNotInstalled),
Toast.LENGTH_LONG).show();
}
}
}
});
Now here you have the function downloadToShare from the class VideoActions:
public String downloadToShare(String token, Activity activity, String videoID, String videoPath, String videoName) {
this.token = token;
this.activity = activity;
this.videoId = videoID;
this.videoPath = videoPath;
this.videoName = videoName;
DownloadToShareClass downloadAction = new DownloadToShareClass();
try {
return downloadAction.execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return null;
} // Close download
And now the downloadToShare class:
class DownloadToShareClass extends AsyncTask<String, String, String> {
String response = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(activity);
pDialog.setMessage("Preparing video to share...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
HttpFileUpload hfu = new HttpFileUpload(videoPath, token);
hfu.Download_File_To_Share(videoName, videoPath);
return "SUCESSFULLY";
}
} // Close DownloadClass
Now the download_file_to_share:
boolean Download_File_To_Share(String fileName, String urlToDownload) {
boolean downloadResult;
try {
downloadResult = DownloadFileToShare(fileName, urlToDownload);
return downloadResult;
} catch (MalformedURLException e) {
return false;
} catch (IOException e) {
return false;
}
}
And for the last the DownloadFileToShare:
// Download video
boolean DownloadFileToShare(String filename, String urlToDownload)
throws MalformedURLException, IOException {
BufferedInputStream in = null;
FileOutputStream fout = null;
try {
URL url = new URL(urlToDownload);
in = new BufferedInputStream(url.openStream());
fout = new FileOutputStream(
Environment.getExternalStorageDirectory() +
File.separator + "vidytape_shared" + File.separator + filename);
byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1) {
fout.write(data, 0, count);
System.out.println(count);
}
} finally {
if (in != null)
in.close();
if (fout != null)
fout.close();
}
return true;
}
My Problem is as you can see on my BaseAdapter code, I'm showing a progress dialog, but it only is shown after all the rest finish (the video download). What is the problem here ? I want that the progressDialog shows when the video is being downloaded...
Thanks in advance
I've found a solution to my own problem. From my BaseAdapter I changed my click listener code to the following and it's working perfectly now:
btnShareFacebook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
videoMoreLayout.setVisibility(View.GONE);
hfu = new HttpFileUpload(videoPathURL[position], token);
final ProgressDialog pDialog = new ProgressDialog(activity);
pDialog.setMessage(activity.getResources().getString(R.string.preparingVideoToShare));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
if (!isOnline()) {
Toast.makeText(activity,
activity.getString(R.string.noInternetConnection),
Toast.LENGTH_SHORT).show();
} else {
try {
String arr[] = videoPathURL[position].split("/upload/videos/");
final String finalVideoName = (arr[arr.length-1]);
final File DoutFile = new File(
Environment.getExternalStorageDirectory() +
File.separator + "vidytape_shared" + File.separator + finalVideoName);
if(!DoutFile.exists()){
pDialog.show();
(new Thread(new Runnable() {
#Override
public void run() {
final String a = hfu.Download_File_To_Share(finalVideoName, videoPathURL[position]);
activity.runOnUiThread(new Runnable() {
public void run() {
if (!a.equalsIgnoreCase("ok")){
pDialog.dismiss();
Toast.makeText(activity,
activity.getResources().getString(R.string.someErrorOccurred),
Toast.LENGTH_LONG).show();
} else {
pDialog.dismiss();
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("video/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(DoutFile));
share.putExtra(Intent.EXTRA_TEXT,
"" + activity.getResources().getString(R.string.app_name));
share.setPackage("com.facebook.katana");
activity.startActivity(share);
}
}
});
}
})).start();
} else {
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("video/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(DoutFile));
share.putExtra(Intent.EXTRA_TEXT,
"" + activity.getResources().getString(R.string.app_name));
share.setPackage("com.facebook.katana");
activity.startActivity(share);
}
} catch (Exception e) {
if(pDialog.isShowing()){
pDialog.dismiss();
}
e.printStackTrace();
Toast.makeText(
activity,
activity.getString(R.string.facebookNotInstalled),
Toast.LENGTH_LONG).show();
}
}
}
});
I hope it can help someone too.

Can you add code to show progressbar in onPreExecute in class DownloadToShareClass which extends AsyncTask ?
Please refer to http://developer.android.com/reference/android/os/AsyncTask.html
From the above link --
onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
class DownloadToShareClass extends AsyncTask<String, String, String> {
private ProgressDialog mdialog;
public DownloadToShareClass(yourActivity activity) {
mdialog = new ProgressDialog(activity);
}
#Override
protected void onPreExecute() {
mdialog.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(Void result) {
if (mdialog.isShowing()) {
mdialog.dismiss();
}
}
}

Related

ProgressBar crashing activity(null object reference / or not visible)

In the following code of my MainActivity (which downloads a json I need in another activity and shows a loading progress bar), which starts before launching HomeActivity, I get a null object reference error (on the getProgress() method), but HomeActivity then starts anyway if I press back button.
I have searched for this kind of error, but the only solution that seems working is the one that let me starts the HomeActivity after some delay, changing setProgress method like this: (but it seems that the bar doesn't change and I don't think it's a real solution to the problem)
public void setProgress(ProgressBar bar, int progress) {
int oldProgress = bar.getProgress();
int totalProgress = oldProgress + progress;
bar.setProgress(totalProgress);
if (bar.getProgress() == 100) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
final Intent intent = new Intent(MainActivity.this, HomePage.class);
startActivity(intent);
}
}, 4000);
}
}
----------------------------------------------------------------------
package ...
import ...
public class MainActivity extends AppCompatActivity {
private ProgressBar progressBar;
private TextView textView;
private OkHttpClient httpClient;
private String url;
private Request request;
private static boolean loaded = false;
private FileInputStream inputStream;
private FileOutputStream outputStream;
private static final String FILE_NAME = "data.txt";
private AlertDialogConnection noResponse;
private AlertDialogConnection noInternet;
private AlertDialogConnection serverError;
private AlertDialogConnection internalError;
public MainActivity(){
this.inputStream = null;
this.outputStream = null;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_main);
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
this.httpClient = new OkHttpClient();
this.url = "my url";
this.request = new Request.Builder().url(url).build();
this.progressBar = findViewById(R.id.progressBar);
this.progressBar.getProgressDrawable().setColorFilter(getResources().getColor(R.color.progressBarColor), android.graphics.PorterDuff.Mode.SRC_IN);
this.textView = findViewById(R.id.textView);
this.noResponse = new AlertDialogConnection();
this.noInternet = new AlertDialogConnection();
this.serverError = new AlertDialogConnection();
this.internalError = new AlertDialogConnection();
checkConnectionStatusAndStart();
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
}
public void checkConnectionStatusAndStart(){
if(checkConnectionStatus())
requestData();
else{
this.noInternet.setTitle("no connection!");
this.noInternet.setText("connection error!");
this.noInternet.show(getSupportFragmentManager(), "no connection!");
}
}
public boolean checkConnectionStatus(){
boolean wifiConnection = false;
boolean mobileConnection = false;
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = null;
if (connectivityManager != null)
networkInfo = connectivityManager.getActiveNetworkInfo();
if((networkInfo != null) && networkInfo.isConnected()){
if(networkInfo.getType() == ConnectivityManager.TYPE_WIFI){
/* Wifi On */
wifiConnection = true;
}
if(networkInfo.getType() == ConnectivityManager.TYPE_MOBILE){
/* Mobile data On */
mobileConnection = true;
}
return (wifiConnection || mobileConnection);
}else{
/* You are not connected */
return false;
}
}
public void requestData(){
textView.setText("waiting server...");
httpClient.connectTimeoutMillis(); //Timeout
httpClient.writeTimeoutMillis();
httpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
if(!call.isExecuted()){
Toast.makeText(getApplicationContext(), "server error!", Toast.LENGTH_LONG).show();
}
Log.d("HTTP-Error", "HTTP error!");
AlertDialogConnection errorDialog = new AlertDialogConnection();
errorDialog.setTitle("server error!");
errorDialog.setText("server error, try later");
errorDialog.show(getSupportFragmentManager(), "messaging error!");
}
#Override
public void onResponse(#NotNull Call call, Response response) throws IOException {
if(response.isSuccessful()){
/* HTTP-code: 200 */
final String body = response.body().string();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
((TextView)findViewById(R.id.textView)).setText("Setting of suggestion variables!");
setProgress(progressBar, 10);
try {
JSONObject json = new JSONObject(body);
try {
((TextView)findViewById(R.id.textView)).setText("retrieving server infos!");
saveJSON(json, getApplicationContext());
} catch (FileNotFoundException e) {
Log.d("File Not Found!", "FileNotFoundException!");
internalError.setTitle("error while saving data!");
internalError.setText("server error, try later");
internalError.show(getSupportFragmentManager(), "error while saving data!");
e.printStackTrace();
} catch (IOException e) {
Log.d("File Not Found!", "IOException!");
internalError.setTitle("error while saving data!");
internalError.setText("server error, try later");
internalError.show(getSupportFragmentManager(), "error while saving data!");
e.printStackTrace();
}
setProgress(progressBar, 90);
MainActivity.loaded = true;
} catch (JSONException e) {
e.printStackTrace();
Log.d("JSON-Error", "parsing JSON error!");
internalError.setTitle("server error!");
internalError.setText("server error, try later");
internalError.show(getSupportFragmentManager(), "JSON messaging error!");
}
}
});
}else{
/* Http-code: 500 */
Log.d("HTTP-Error", "server error!");
serverError.setTitle("server error!");
serverError.setText("server error");
serverError.show(getSupportFragmentManager(), "server error!");
}
}
});
}
public void setProgress(ProgressBar bar, int progress){
int oldProgress = bar.getProgress();
int totalProgress = oldProgress + progress;
bar.setProgress(totalProgress);
if(bar.getProgress() == 100){
Intent intent = new Intent(this, HomePage.class);
startActivity(intent);
this.onDestroy();
}
}
private void saveJSON(JSONObject json, Context context) throws IOException {
outputStream = null;
try{
outputStream = context.openFileOutput(FILE_NAME, MODE_PRIVATE);
outputStream.write(json.toString().getBytes());
}finally {
if(outputStream != null){
outputStream.close();
}
}
}
public JSONObject loadJSON(Context context) throws IOException, JSONException {
inputStream = context.openFileInput(FILE_NAME);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
JSONObject jsonObject = new JSONObject(reader.readLine());
inputStream.close();
return jsonObject;
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onDestroy() {
this.httpClient = null;
this.noResponse = null;
this.noInternet = null;
this.serverError = null;
this.internalError = null;
this.request = null;
this.textView = null;
this.progressBar = null;
this.url = null;
super.onDestroy();
}
#Override
protected void onResume() {
if(!loaded){
checkConnectionStatusAndStart();
}
super.onResume();
}
#Override
protected void onRestart() {
if(!loaded){
checkConnectionStatusAndStart();
}
super.onRestart();
}
#Override
protected void onPause() {
if(!loaded ){
checkConnectionStatusAndStart();
}
super.onPause();
}
}

why do i get th java.lang.RuntimeException: Unable to start activity ComponentInfo

Hi guys im making a auto update after following a tutorial online then editing the code to suit my needs.. but im getting this error in my logcat
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.harrops.h20droidapp/com.example.harrops.h20droidapp.Homescreen}: android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.harrops.h20droidapp/com.example.harrops.h20droidapp.UpdateService}; have you declared this activity in your AndroidManifest.xml?
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
can some one please help me
this is my service class
public class UpdateService extends Service {
public UpdateService() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
String url = "<MY Link for version>";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response != null) {
boolean resp = response.contains("<div class='post-body entry-content' id='post-body-6791062644900393367' itemprop='description articleBody'>\n" +
"1.1.8\n" +
"<div style='clear: both;'></div>");
if (!resp) {
//Dialog to show update
Intent intent1 = new Intent(UpdateService.this, UpdateDialog.class);
intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent1);
} else {
Toast.makeText(UpdateService.this, "No New Update Found..", Toast.LENGTH_LONG).show();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
queue.add(stringRequest);
return Service.START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
then this is my dialog class
public static Button btn;
public static String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Update";
public static File Dir = new File(path);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidAuthSession session = buildSession();
dropboxAPI = new DropboxAPI<AndroidAuthSession>(session);
Dir.mkdir();
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setIcon(R.mipmap.ic_launcher);
alertDialog.setTitle("update");
alertDialog.setMessage("New update Available...");
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "UPDATE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
DownloadFromDropboxFromPath(path + "downloadFileFromDropbox", "Update/Myupdate.apk");
}
});
alertDialog.show();
}
static DropboxAPI<AndroidAuthSession> dropboxAPI;
private static final String APP_KEY = "********* **** ** **";
private static final String APP_SECRET = "XXX XX X X XX X";
private static final String ACCESSTOKEN = "xx x x xxx x x x x";
private DropboxAPI.UploadRequest request;
private AndroidAuthSession buildSession() {
AppKeyPair appKeyPair = new AppKeyPair(APP_KEY, APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appKeyPair);
session.setOAuth2AccessToken(ACCESSTOKEN);
return session;
}
static final int UploadFromSelectApp = 9501;
static final int UploadFromFilemanager = 9502;
public static String DropboxUploadPathFrom = "";
public static String DropboxUploadName = "";
public static String DropboxDownloadPathFrom = "";
public static String DropboxDownloadPathTo = "";
private void UploadToDropboxFromPath(String uploadPathFrom, String uploadPathTo) {
Toast.makeText(getApplicationContext(), "Upload file ...", Toast.LENGTH_SHORT).show();
final String uploadPathF = uploadPathFrom;
final String uploadPathT = uploadPathTo;
Thread th = new Thread(new Runnable() {
public void run() {
File tmpFile = null;
try {
tmpFile = new File(uploadPathF);
} catch (Exception e) {
e.printStackTrace();
}
FileInputStream fis = null;
try {
fis = new FileInputStream(tmpFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
dropboxAPI.putFileOverwrite(uploadPathT, fis, tmpFile.length(), null);
} catch (Exception e) {
}
getMain().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "File successfully uploaded.", Toast.LENGTH_SHORT).show();
}
});
}
});
th.start();
}
private void UploadToDropboxFromSelectedApp(String uploadName) {
DropboxUploadName = uploadName;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "Upload from ..."), UploadFromSelectApp);
}
private void UploadToDropboxFromFilemanager(String uploadName) {
DropboxUploadName = uploadName;
Intent intent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
intent.putExtra("CONTENT_TYPE", "*/*");
intent.addCategory(Intent.CATEGORY_DEFAULT);
startActivityForResult(intent, UploadFromFilemanager);
}
private void DownloadFromDropboxFromPath(String downloadPathTo, String downloadPathFrom) {
DropboxDownloadPathTo = downloadPathTo;
DropboxDownloadPathFrom = downloadPathFrom;
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Download file ...", Toast.LENGTH_SHORT).show();
Thread th = new Thread(new Runnable() {
public void run() {
File file = new File(DropboxDownloadPathTo + DropboxDownloadPathFrom.substring(DropboxDownloadPathFrom.lastIndexOf('.')));
if (file.exists()) file.delete();
try {
FileOutputStream outputStream = new FileOutputStream(file);
UpdateDialog.dropboxAPI.getFile(DropboxDownloadPathFrom, null, outputStream, null);
getMain().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "File successfully downloaded.", Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
th.start();
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == UploadFromFilemanager) {
final Uri currFileURI = intent.getData();
final String pathFrom = currFileURI.getPath();
Toast.makeText(getApplicationContext(), "Upload file ...", Toast.LENGTH_SHORT).show();
Thread th = new Thread(new Runnable() {
public void run() {
getMain().runOnUiThread(new Runnable() {
#Override
public void run() {
UploadToDropboxFromPath(pathFrom, "/db-test/" + DropboxUploadName + pathFrom.substring(pathFrom.lastIndexOf('.')));
Toast.makeText(getApplicationContext(), "File successfully uploaded.", Toast.LENGTH_SHORT).show();
}
});
}
});
th.start();
}
if (requestCode == UploadFromSelectApp) {
Toast.makeText(getApplicationContext(), "Upload file ...", Toast.LENGTH_SHORT).show();
final Uri uri = intent.getData();
DropboxUploadPathFrom = getPath(getApplicationContext(), uri);
if (DropboxUploadPathFrom == null) {
DropboxUploadPathFrom = uri.getPath();
}
Thread th = new Thread(new Runnable() {
public void run() {
try {
final File file = new File(DropboxUploadPathFrom);
InputStream inputStream = getContentResolver().openInputStream(uri);
dropboxAPI.putFile("/db-test/" + DropboxUploadName + file.getName().substring(file.getName().lastIndexOf("."),
file.getName().length()), inputStream, file.length(), null, new ProgressListener() {
#Override
public long progressInterval() {
return 100;
}
#Override
public void onProgress(long arg0, long arg1) {
}
});
getMain().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "File successfully uploaded.", Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
th.start();
}
super.onActivityResult(requestCode, resultCode, intent);
}
public String getPath(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = {MediaStore.Images.Media.DATA, MediaStore.Video.Media.DATA, MediaStore.Audio.Media.DATA};
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String s = cursor.getString(column_index);
if (s != null) {
cursor.close();
return s;
}
} catch (Exception e) {
}
try {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
cursor.moveToFirst();
String s = cursor.getString(column_index);
if (s != null) {
cursor.close();
return s;
}
} catch (Exception e) {
}
try {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
cursor.moveToFirst();
String s = cursor.getString(column_index);
cursor.close();
return s;
} finally {
if (cursor != null) {
cursor.close();
}
}
}
public UpdateDialog getMain() {
return this;
}
}
then finally i call it in my homescreen class. with an intent
Intent intent = new Intent(Homescreen.this, UpdateService.class);
startActivity(intent);
UpdateService is a Service. It is not an Activity. To start a service, you call startService(), not startActivity().
As UpdateService is a service you have to start it by startService() method like #CommonsWare mentioned above. Also don't forget to add your service in Manifest file.
UpdateService is not an activity, It's a class that is extending services.
I think u r a very beginner.
Please go to Udacity and learn the concepts before tingling with android, otherwise, u will waste lot of your time in finding a copy-paste solution.

Android Need help! How to make Tcp Client receive data from server?

I want to make a TCP client that can sent and receive data for server. I use Hercules(TCP/UDP test program) as Server. My code can send string "Submit" to Server. I try to make my code can receive data from Hercules but it not work.what I have to do for edit it?
This is my MainActivity code
public class MainActivity extends Activity {
// Used to reference UI elements of main.xml
private TextView text,serverResponse;
private EditText ipBox;
private EditText portBox;
private ToggleButton connect;
private Button send;
private static final String TAG = "CClient";
private String ipAddress;
private Socket client;
private DataOutputStream outToServer;
private DataInputStream inFromServer;
private boolean connected = false;
private final int START = 0xffffff;
private final int msgBoxHint = START;
private final int appendText = START + 1;
Toast mytoast , savetoast;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
Log.d(TAG, "Here 1");
ipAddress = getLocalIpAddress();
Log.d(TAG, "Get local IP="+ ipAddress);
text = (TextView) findViewById(R.id.text);
ipBox = (EditText) findViewById(R.id.ipBox);
serverResponse = (TextView) findViewById(R.id.response);
portBox = (EditText) findViewById(R.id.portBox);
send = (Button) findViewById(R.id.send);
send.setOnClickListener(buttonsendOnClickListener);
connect = (ToggleButton) findViewById(R.id.connect);
connect.setOnClickListener(buttonConnectOnClickListener);
Button buttonExit = (Button) findViewById(R.id.btnExit);
buttonExit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d(TAG, "Exit");
Log.d(TAG, "Disconnect" );
if(client != null)
{
try {
client.close();
} catch (IOException e) {
Log.d(TAG, "Disconnect"+e.toString() );
}
}
finish();
}
});
}
OnClickListener buttonConnectOnClickListener = new OnClickListener() {
/** Manages all button clicks from the screen */
#TargetApi(Build.VERSION_CODES.HONEYCOMB) #Override
public void onClick(View arg0) {
switch(arg0.getId())
{
case R.id.connect:
if(connect.isChecked())
{
Log.d(TAG, "Connect" );
EditText edIP = (EditText) findViewById(R.id.ipBox);
String ed_textIP = edIP.getText().toString().trim();
if(ed_textIP.isEmpty() || ed_textIP.length() == 0 || ed_textIP.equals("") || ed_textIP == null )
{
Toast.makeText(MainActivity.this, "IP Address or PORT is incorrect", Toast.LENGTH_SHORT).show();
Log.d(TAG, "IP Address or PORT is incorrect");
}
setValues(R.id.connect,true);
setValues(R.id.send,true);
setValues(R.id.ipBox,false);
String tMsg = welcomeMsg.toString();
MyClientTask myClientTask = new MyClientTask(ipBox
.getText().toString(), Integer.parseInt(portBox
.getText().toString()),
tMsg);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
myClientTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
else
myClientTask.execute();
}
else
{ /*Toast.makeText(this, ipBox.getText(), Toast.LENGTH_LONG).show();*/
Log.d(TAG, "Disconnect" );
if(client != null)
{
try {
client.close();
} catch (IOException e) {
Log.d(TAG, "Disconnect"+e.toString() );
}
setText(R.id.text,"Press the connect button to start the client");
setText(msgBoxHint,"");
setValues(R.id.connect,false);
setValues(R.id.ipBox,true);
setValues(R.id.send,false);
}
else
{
setValues(R.id.connect,false);
}
}
break;
}
}
};
public class MyClientTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
String msgToServer;
MyClientTask(String addr, int port, String msgTo) {
dstAddress = addr;
dstPort = port;
msgToServer = msgTo;
}
protected Void doInBackground(Void... Arg0) {
Log.d(TAG, "InBackground");
Socket socket = null;
DataOutputStream outToServer = null;
DataInputStream inFromServer = null;
try {
client = new Socket(dstAddress, dstPort);
outToServer = new DataOutputStream(client.getOutputStream());
inFromServer = new DataInputStream(new BufferedInputStream(client.getInputStream())); // Input stream <- from server
}catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.d(TAG, "InBackground 1");
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
mytoast = Toast.makeText(MainActivity.this, "Error UnknownHostException",
Toast.LENGTH_SHORT);
mytoast.show();
setValues(R.id.send,false);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mytoast.cancel();
}
}, 500);
}
});
} catch (IOException e) {
Log.d(TAG, "InBackground 2");
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
mytoast = Toast.makeText(MainActivity.this, "Error IOException",
Toast.LENGTH_SHORT);
mytoast.show();
setValues(R.id.connect,false);
setValues(R.id.send,false);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mytoast.cancel();
}
}, 500);
}
});
}finally {
Log.d(TAG, "InBackground 3");
if (socket != null) {
try {
socket.close();
Log.d(TAG, "InBackground 3.11");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d(TAG, "InBackground 3.12");
}
}
Log.d(TAG, "InBackground 3.1");
}
Log.d(TAG, "InBackground 4");
return null;
}
#Override
protected void onPostExecute(Void result) {
serverResponse.setText(response);
super.onPostExecute(result);
}
}
OnClickListener buttonsendOnClickListener = new OnClickListener() {
/** Manages all button clicks from the screen */
#TargetApi(Build.VERSION_CODES.HONEYCOMB) #Override
public void onClick(View arg0) {
switch(arg0.getId())
{
case R.id.send:
Log.d(TAG, "Sent" );
String sentence = "Submit";
String recieve = "";
serverResponse = (TextView) findViewById(R.id.response);
try {
outToServer = new DataOutputStream(client.getOutputStream());
inFromServer = new DataInputStream(new BufferedInputStream(client.getInputStream()));
Log.d(TAG, "Sent 1-1" );
if(sentence != null){
outToServer.writeUTF(sentence);
outToServer.flush();
}
/*
*
*
*
*
*
*/
Log.d(TAG, "Sent 1-2"+ recieve);
} catch (IOException e) {
setValues(R.id.ipBox,true);
setValues(R.id.connect,false);
setValues(R.id.send,false);
}
break;
}
}
};
private String getLocalIpAddress() {
Log.d(TAG, "Here 2");
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
Log.d(TAG, "Here 3");
WifiInfo info = wifi.getConnectionInfo();
Log.d(TAG, "Here 4");
return Formatter.formatIpAddress(info.getIpAddress());
}
private void setText(int view, String content)
{
switch(view)
{
case R.id.ipBox: ipBox.setText(content); break;
case R.id.text: text.setText(content+"\n\n"); break;
case appendText: text.append(content+"\n\n"); break;
}
}
private void setValues(int view, boolean value)
{
switch(view)
{
case R.id.ipBox: ipBox.setEnabled(value); break;
case R.id.send: send.setEnabled(value); break;
case R.id.connect: connect.setChecked(value); break;
}
}
}
I think, I have to add receive code in buttonsendOnClickListener near /*****/.
Do not work with sockets in main (gui) thread. Use AsyncTask!
Android fails if work with sockets in main (gui) thread.
Example:
new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
// do in main thread before
}
#Override
protected Void doInBackground(Void... v) {
// do in thread, use sockets
return null;
}
#Override
protected void onPostExecute(Void v) {
super.onPostExecute(integer);
// do in main thread after
}
}.execute();
Learn about AsyncTask advance.

How to display lat/long markers on google map v2 android

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.

Missing access tokens

This is the code i have currently, but I am unable to get the access tokens from my callback, any tips or hints will be appreciated.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tweetr);
Button tweetr = (Button)findViewById(R.id.tweetr);
//create a new twitter configuration using user details
tweetTwitter = new TwitterFactory().getInstance();
tweetTwitter.setOAuthConsumer(TWIT_KEY, TWIT_SECRET);
//create a twitter instance
// tweetTwitter = new TwitterFactory(twitConf).getInstance();
tweetr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dt.execute();
}
});
}
public class TweetTask extends AsyncTask<Object, Void, String> {
#Override
protected String doInBackground(Object... values) {
/* try {
//requestToken = tweetTwitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())));
*/
try {
requestToken = tweetTwitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
String authUrl = requestToken.getAuthenticationURL();
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
Log.d("URI", "DONE");
super.onPostExecute(result);
}
}
#Override
protected void onResume() {
super.onResume();
final Uri uri = getIntent().getData();
if(uri != null ){
Log.d("URI", uri.toString());
Thread th = new Thread(){
public void run(){
AccessToken accessToken;
try {
String verifier = uri.getQueryParameter("oauth_verifier");
String oauthToken = uri.getQueryParameter("oauth_token");
accessToken = tweetTwitter.getOAuthAccessToken(verifier);
//String token = accessToken.getToken(), secret = accessToken.getTokenSecret();
} catch (TwitterException ex) {
Log.e("Main.onNewIntent", "" + ex.getMessage());
}
}};
th.start();
}else
Log.d("URI", "FAILED");
}
}
I had to use the same requestToken in order to gain access with my app, so I had to edit the manifest file to allow only one instance of the activity to run after returning from webview login panel. That solved it for me.

Categories

Resources