Display success message after file is copied - java

I am fairly new to Android development so I thought I would start off with a basic app. When a button is pressed, it copies a file to the location written in the code (see my code below). When I press the install button and the file is copied to its location, I want a toast message to display "Successfully Installed or Error while copying file". How would I implement this?
public class TrialActivity extends Activity {
private ProgressDialog progressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
runDialog(5);
}
private void runDialog(final int seconds)
{
progressDialog = ProgressDialog.show(this, "Please Wait...", "unpacking patch in progress");
new Thread(new Runnable(){
public void run(){
try {
Thread.sleep(seconds * 1000);
progressDialog.dismiss();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
((Button)findViewById(R.id.button1)).setOnClickListener(new View.OnClickListener()
{
public void onClick(View paramView)
{
}
{
InputStream in = null;
OutputStream out = null;
String filename="savegame.bin";
try {
in = getResources().openRawResource(R.raw.savegame);
out = new FileOutputStream("/sdcard/Android/data/files/" + filename);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(Exception e) {
Log.e("tag", e.getMessage());
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
}
);
}
}

use next code:
private class AsyncTaskDialog extends AsyncTask<Void, Void, Void> {
Toast toastSuccess;
boolean flagSuccessCopy =false;
protected void onPreExecute() {
super.onPreExecute();
}
}
protected Boolean doInBackground(Void... params) {
copyFiles();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if (getActivity() != null) {
if(flagSuccessCopy){
toastSuccess = Toast.makeText(context, "Success", duration);
}else{
toastSuccess = Toast.makeText(context, "Error", duration);
}
toast.show();
}
}

Allows to copy any file from any application to SD card
import ru.gelin.android.sendtosd.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.widget.ProgressBar;
import android.widget.TextView;
public class ProgressDialog extends AlertDialog implements Progress {
/** Activity for which the dialog is created */
Activity activity;
/** Progress manager for the dialog */
ProgressManager manager = new ProgressManager();
/**
* Creates the customized progress dialog for
* activity.
*/
protected ProgressDialog(Activity activity) {
super(activity);
}
#Override
public void setFiles(int files) {
synchronized (manager) {
manager.setFiles(files);
}
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
synchronized (manager) {
updateTotalProgress();
}
}
});
}
#Override
public void nextFile(final File file) {
synchronized (manager) {
manager.nextFile(file);
}
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
synchronized (manager) {
updateFileName(file);
updateFileProgress();
updateTotalProgress();
}
}
});
}
#Override
public void processBytes(long bytes) {
synchronized (manager) {
manager.processBytes(bytes);
}
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
synchronized (manager) {
updateFileProgress();
}
}
});
}
void updateTotalProgress() {
ProgressBar progress = (ProgressBar)findViewById(R.id.total_progress);
progress.setMax(manager.getFiles());
progress.setProgress(manager.getFile());
TextView text = (TextView)findViewById(R.id.total_files);
text.setText(getContext().getString(R.string.files_progress,
manager.getFile(), manager.getFiles()));
}
void updateFileName(File file) {
if (file == null) {
return;
}
TextView view = (TextView)findViewById(R.id.file_name);
view.setText(file.getName());
}
void updateFileProgress() {
ProgressBar progress = (ProgressBar)findViewById(R.id.file_progress);
if (manager.getProgressInUnits() < 0) {
progress.setIndeterminate(true);
} else {
progress.setIndeterminate(false);
progress.setMax((int)(manager.getSizeInUnits() * 10));
progress.setProgress((int)(manager.getProgressInUnits() * 10));
}
TextView text = (TextView)findViewById(R.id.file_size);
text.setText(getContext().getString(manager.getSizeUnit().progressString,
manager.getProgressInUnits(), manager.getSizeInUnits()));
}
}
source: http://code.google.com/p/sendtosd-android/source/browse/src/ru/gelin/android/sendtosd/progress/ProgressDialog.java?spec=svn0933973391a12bee4759a32f5776864c64022d71&r=0933973391a12bee4759a32f5776864c64022d71

Related

Getting the value from textview

Hello guys I got a code that I do for my project, the code is to get the value of the heartbeat sensor from Arduino to my android phone using Bluetooth. So far it's going well it can send the value to my app without a problem. but the problem now is I want to get the value of it so I can use my algorithm with it, but seems like I got in a pickle now.
Here is the code :
package com.test.aplikasirevisi;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
public class MonitoringScreen extends Activity {
private static final String TAG = "BlueTest5-MainActivity";
private int mMaxChars = 50000;//Default
private UUID mDeviceUUID;
private BluetoothSocket mBTSocket;
private ReadInput mReadThread = null;
private boolean mIsUserInitiatedDisconnect = false;
private TextView mTxtReceive;
private Button mBtnClearInput;
private ScrollView scrollView;
private CheckBox chkScroll;
private CheckBox chkReceiveText;
private boolean mIsBluetoothConnected = false;
private BluetoothDevice mDevice;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_monitoring_screen);
ActivityHelper.initialize(this);
Intent intent = getIntent();
Bundle b = intent.getExtras();
mDevice = b.getParcelable(MainActivity.DEVICE_EXTRA);
mDeviceUUID = UUID.fromString(b.getString(MainActivity.DEVICE_UUID));
mMaxChars = b.getInt(MainActivity.BUFFER_SIZE);
Log.d(TAG, "Ready");
mTxtReceive = (TextView) findViewById(R.id.txtReceive);
chkScroll = (CheckBox) findViewById(R.id.chkScroll);
chkReceiveText = (CheckBox) findViewById(R.id.chkReceiveText);
scrollView = (ScrollView) findViewById(R.id.viewScroll);
mBtnClearInput = (Button) findViewById(R.id.btnClearInput);
mTxtReceive.setMovementMethod(new ScrollingMovementMethod());
mBtnClearInput.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
mTxtReceive.setText("");
}
});
}
private class ReadInput implements Runnable{
private boolean bStop = false;
private Thread t;
public ReadInput() {
t = new Thread(this, "Input Thread");
t.start();
}
public boolean isRunning() {
return t.isAlive();
}
#Override
public void run() {
InputStream inputStream;
try {
inputStream = mBTSocket.getInputStream();
while (!bStop) {
byte[] buffer = new byte[256];
if (inputStream.available() > 0) {
inputStream.read(buffer);
int i;
/*
* This is needed because new String(buffer) is taking the entire buffer i.e. 256 chars on Android 2.3.4 http://stackoverflow.com/a/8843462/1287554
*/
for (i = 0; i < buffer.length && buffer[i] != 0; i++) {
}
final String strInput = new String(buffer, 0, i);
/*
* If checked then receive text, better design would probably be to stop thread if unchecked and free resources, but this is a quick fix
*/
if (chkReceiveText.isChecked()) {
mTxtReceive.post(new Runnable() {
#Override
public void run() {
mTxtReceive.append(strInput);
int txtLength = mTxtReceive.getEditableText().length();
if(txtLength > mMaxChars){
mTxtReceive.getEditableText().delete(0, txtLength - mMaxChars);
System.out.println(mTxtReceive.getText().toString());
}
if (chkScroll.isChecked()) { // Scroll only if this is checked
scrollView.post(new Runnable() { // Snippet from http://stackoverflow.com/a/4612082/1287554
#Override
public void run() {
scrollView.fullScroll(View.FOCUS_DOWN);
}
});
}
}
});
}
}
Thread.sleep(500);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void stop() {
bStop = true;
}
}
private class DisConnectBT extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
if (mReadThread != null) {
mReadThread.stop();
while (mReadThread.isRunning())
; // Wait until it stops
mReadThread = null;
}
try {
mBTSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mIsBluetoothConnected = false;
if (mIsUserInitiatedDisconnect) {
finish();
}
}
}
private void msg(String s) {
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
#Override
protected void onPause() {
if (mBTSocket != null && mIsBluetoothConnected) {
new DisConnectBT().execute();
}
Log.d(TAG, "Paused");
super.onPause();
}
#Override
protected void onResume() {
if (mBTSocket == null || !mIsBluetoothConnected) {
new ConnectBT().execute();
}
Log.d(TAG, "Resumed");
super.onResume();
}
#Override
protected void onStop() {
Log.d(TAG, "Stopped");
super.onStop();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
}
private class ConnectBT extends AsyncTask<Void, Void, Void> {
private boolean mConnectSuccessful = true;
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(MonitoringScreen.this, "Hold on", "Connecting");// http://stackoverflow.com/a/11130220/1287554
}
#Override
protected Void doInBackground(Void... devices) {
try {
if (mBTSocket == null || !mIsBluetoothConnected) {
mBTSocket = mDevice.createInsecureRfcommSocketToServiceRecord(mDeviceUUID);
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
mBTSocket.connect();
}
} catch (IOException e) {
// Unable to connect to device
e.printStackTrace();
mConnectSuccessful = false;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (!mConnectSuccessful) {
Toast.makeText(getApplicationContext(), "Could not connect to device. Is it a Serial device? Also check if the UUID is correct in the settings", Toast.LENGTH_LONG).show();
finish();
} else {
msg("Connected to device");
mIsBluetoothConnected = true;
mReadThread = new ReadInput(); // Kick off input reader
}
progressDialog.dismiss();
}
}
}
What i want is to get the value of mTxtReceive on this :
int txtLength = mTxtReceive.getEditableText().length();
if(txtLength > mMaxChars){
mTxtReceive.getEditableText().delete(0, txtLength - mMaxChars);
System.out.println(mTxtReceive.getText().toString());
}
I used System.out.println for seeing if i got the value but in the log it didn't show any thing.
So i need you guys wisdom for this any help?
Your view mTextReceive seems to be a TextView and therefore not editable:
private TextView mTxtReceive;
If it's not an EditText (editable) mTxtReceive.getEditableText will return null see docs
and getText should be called instead see docs.
Therefore your condition might always resolve from
if(txtLength > mMaxChars) into if(null > 50000) which is always false (or actually it might even crash before) and therefore your code inside the if-block is never executed
Try:
// recommended for debugging. Check if this is even called and if text length is really longer than max chars
Log.d(TAG, "text length:" + mTxtReceive.getText().length());
int txtLength = mTxtReceive.getText().length();
if(txtLength > mMaxChars){
// not sure what operation you want to do here but leave out for debugging
Log.d(TAG, "text longer than allowed:" + mTxtReceive.getText().toString());
}
Also use Log.d instead of System.out.println since your log might otherwise not be forwarded to Logcat. Also are you sure this block is executed at all? I'd put a Log.d(TAG, "text length:" + mTxtReceive.getText().length()); outside of the condition for debugging purposes. And finally the obvious question would be if the txtLength is even longer than max chars (and that would be quite a long text with 50000 chars). But you can verify that simply with the recommended log outside the block as well.

Problem with accessing the views from exception within asyncTask

I am having a problem which is I think that I can't access th,e ListView from the asyncTask
Actually, I really don't know the real problem here
Let me show you what is happening
I have an activity which is executing AsyncTask and creates HttpURLConnection. Sometimes I get an exception (ProtocolException) because the stream un-expectedly ends.
So, I created a handler for this exception that calls a function or a method inside the class of the activity to display a message to the user
Here is a picture so you understand what is my project.
image
the problem here whenever the exception is thrown, the same function/method that I use to add the text to the listView is called, but after it called the listView disappear, but when I minimize the soft keyboard manually the everything becomes fine.
the structure of my class is
public class MainActivity extends AppCompatActivity
{
protected void onCreate(Bundle savedInstanceState)
{
addMessageToListView()//works fin here
}
protected void addMessage(String message, int userMessage, ListView listView) // the function
{
try
{
messages.add(new Message(message,userMessage));
MessagesAdapter messagesAdapter = new MessagesAdapter(messages, getBaseContext());
messagesAdapter.notifyDataSetChanged();
listView.setAdapter(messagesAdapter);
}
catch (Exception exception)
{
}
}
private class HttpPostAsyncTask extends AsyncTask<String, Void, String>
{
...
#Override
protected void onPostExecute(String result)
{
try
{
addMessageToListView()//works fin here
}
catch (Exception exception)
{
}
}
protected String doInBackground(String... params)
{
String result = "";
for (int i = 0; i <= 0; ++i)
{
result = this.invokePost(params[i], this.postData);
}
return result;
}
private String invokePost(String requestURL, HashMap<String, String> postDataParams)// called from doInBackground
{
try
{
addMessageToListView()//works fin here
}
catch (Exception exception)
{
addMessageToListView()//not orking here
}
}
}
}
I don't know how to explain more actually.
You can change Views only in mainthread of your app. The doInBackground doesn't run in mainthread of your app.
Solved by adding:
new Thread()
{
#Override
public void run()
{
MainActivity.this.runOnUiThread(new Runnable()
{
#Override
public void run()
{
addMessageToListView()//not orking here
}
});
super.run();
}
}.start();
Editing the previous code in my question:
public class MainActivity extends AppCompatActivity
{
protected void onCreate(Bundle savedInstanceState)
{
addMessageToListView()//works fin here
}
protected void addMessage(String message, int userMessage, ListView listView) // the function
{
try
{
messages.add(new Message(message,userMessage));
MessagesAdapter messagesAdapter = new MessagesAdapter(messages, getBaseContext());
messagesAdapter.notifyDataSetChanged();
listView.setAdapter(messagesAdapter);
}
catch (Exception exception)
{
}
}
private class HttpPostAsyncTask extends AsyncTask<String, Void, String>
{
...
#Override
protected void onPostExecute(String result)
{
try
{
addMessageToListView()//works fin here
}
catch (Exception exception)
{
}
}
protected String doInBackground(String... params)
{
String result = "";
for (int i = 0; i <= 0; ++i)
{
result = this.invokePost(params[i], this.postData);
}
return result;
}
private String invokePost(String requestURL, HashMap<String, String> postDataParams)// called from doInBackground
{
try
{
addMessageToListView()//works fin here
}
catch (Exception exception)
{
new Thread()
{
#Override
public void run()
{
MainActivity.this.runOnUiThread(new Runnable()
{
#Override
public void run()
{
addMessageToListView()//not orking here
}
});
super.run();
}
}.start();
}
}
}
}

Android Tumblr login issue "JumblrException: Not Authorized"

Why following code giving me such type of exception com.tumblr.jumblr.exceptions.JumblrException: Not Authorized
I saw this question , but i am not able to resolved this issue...plz help me
public class MainActivity extends Activity implements OnClickListener {
private static final String TAG = "TumblrDemo";
private static final String PREFERENCE_NAME = "tumblr";
public static final String REQUEST_TOKEN_URL = "https://www.tumblr.com/oauth/request_token";
public static final String ACCESS_TOKEN_URL = "https://www.tumblr.com/oauth/access_token";
public static final String AUTH_URL = "https://www.tumblr.com/oauth/authorize";
// public static final String CALLBACK_URL =
// "tumblrdemo://tumblrdemo.com/ok";
public static final String OAUTH_CALLBACK_SCHEME = "oauthflow-tumblr";
public static final String OAUTH_CALLBACK_HOST = "callback";
public static final String CALLBACK_URL = OAUTH_CALLBACK_SCHEME + "://"
+ OAUTH_CALLBACK_HOST;
private TransparentProgressDialog progressDialog;
private Button loginTumblrBtn;
private SharedPreferences preferences;
private CommonsHttpOAuthConsumer consumer;
private CommonsHttpOAuthProvider provider;
private String token, token_secret, oauth_verifier;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
consumer = new CommonsHttpOAuthConsumer(Constant.CONSUMER_KEY,
Constant.CONSUMER_SECRET);
provider = new CommonsHttpOAuthProvider(REQUEST_TOKEN_URL,
ACCESS_TOKEN_URL, AUTH_URL);
preferences = getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
loginTumblrBtn = (Button) findViewById(R.id.login_tumblr);
Uri uri = this.getIntent().getData();
if (uri != null && uri.getScheme().equals(OAUTH_CALLBACK_SCHEME)) {
loginTumblrBtn.setText(getString(R.string.logout_tumblr));
try {
oauth_verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
Log.d(TAG, uri.toString());
// provider.retrieveAccessToken(consumer, oauth_verifier);
// token = consumer.getToken();
// token_secret = consumer.getTokenSecret();
token = uri.getQueryParameter("oauth_token");
token_secret = uri.getQueryParameter("oauth_verifier");
consumer.setTokenWithSecret(token, token_secret);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(Constant.TOKEN, token);
editor.putString(Constant.TOKEN_SECRET, token_secret);
editor.commit();
getUserDetails();
} catch (Exception e) {
e.printStackTrace();
}
} else {
loginTumblrBtn.setText(getString(R.string.login_tumblr));
}
loginTumblrBtn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.login_tumblr) {
if (isTumblrConnected()) {
SharedPreferences.Editor editor = preferences.edit();
editor.putString(Constant.TOKEN, null);
editor.putString(Constant.TOKEN_SECRET, null);
editor.commit();
loginTumblrBtn.setText(getString(R.string.login_tumblr));
} else {
new AsyncTaskClass().execute();
}
}
}
private boolean isTumblrConnected() {
return preferences.getString(Constant.TOKEN, null) != null;
}
private class AsyncTaskClass extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
String authUrl = provider.retrieveRequestToken(consumer,
CALLBACK_URL);
startActivity(new Intent("android.intent.action.VIEW",
Uri.parse(authUrl)));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new TransparentProgressDialog(MainActivity.this,
R.drawable.loading);
progressDialog.show();
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (progressDialog != null && progressDialog.isShowing())
progressDialog.dismiss();
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if (isTumblrConnected()) {
token = preferences.getString(Constant.TOKEN, null);
token_secret = preferences.getString(Constant.TOKEN_SECRET, null);
loginTumblrBtn.setText(getString(R.string.logout_tumblr));
getUserDetails();
} else {
loginTumblrBtn.setText(getString(R.string.login_tumblr));
}
}
private void getUserDetails() {
new Thread(new Runnable() {
#Override
public void run() {
try {
JumblrClient client = new JumblrClient(
Constant.CONSUMER_KEY, Constant.CONSUMER_SECRET);
client.setToken(token, token_secret);
// Write the user's name
User user = client.user();
System.out.println(user.getName());
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
Ya finally got solution after too much work, i misunderstood between access token and request token.
Here it is working solution for above issue.Hope it works for you.
public class MainActivity extends Activity implements OnClickListener {
private Button loginTumblrBtn;
private CommonsHttpOAuthConsumer consumer;
private CommonsHttpOAuthProvider provider;
private SharedPreferences preferences;
private Uri uri;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
preferences = getSharedPreferences("tumblr", Context.MODE_PRIVATE);
loginTumblrBtn = (Button) findViewById(R.id.login_tumblr);
loginTumblrBtn.setOnClickListener(this);
consumer = new CommonsHttpOAuthConsumer(Constant.CONSUMER_KEY,
Constant.CONSUMER_SECRET);
provider = new CommonsHttpOAuthProvider(Constant.REQUEST_TOKEN_URL,
Constant.ACCESS_TOKEN_URL, Constant.AUTH_URL);
uri = this.getIntent().getData();
if (uri != null
&& uri.getScheme().equals(Constant.OAUTH_CALLBACK_SCHEME)) {
loginTumblrBtn.setText(getString(R.string.logout_tumblr));
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
consumer.setTokenWithSecret(
preferences.getString("requestToken", ""),
preferences.getString("requestSecret", ""));
provider.setOAuth10a(true);
provider.retrieveAccessToken(consumer,
uri.getQueryParameter(OAuth.OAUTH_VERIFIER));
consumer.setTokenWithSecret(consumer.getToken(),
consumer.getTokenSecret());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("token", consumer.getToken());
editor.putString("token_secret",
consumer.getTokenSecret());
editor.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
loginTumblrBtn.setText(getString(R.string.login_tumblr));
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.login_tumblr:
if (preferences.getString("token", null) != null) {
loginTumblrBtn.setText(getString(R.string.login_tumblr));
SharedPreferences.Editor editor = preferences.edit();
editor.putString("token", null);
editor.putString("token_secret", null);
editor.commit();
} else {
progressDialog = ProgressDialog.show(this, "Loading",
"Please Wait...");
new Thread(new Runnable() {
#Override
public void run() {
try {
String authUrl = provider.retrieveRequestToken(
consumer, Constant.CALLBACK_URL);
SharedPreferences.Editor editor = preferences
.edit();
editor.putString("requestToken",
consumer.getToken());
editor.putString("requestSecret",
consumer.getTokenSecret());
editor.commit();
startActivity(new Intent(
"android.intent.action.VIEW", Uri
.parse(authUrl)));
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
break;
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if (preferences.getString("token", null) != null) {
loginTumblrBtn.setText(getString(R.string.logout_tumblr));
} else {
loginTumblrBtn.setText(getString(R.string.login_tumblr));
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
and put this intent-filter code inside manifest>application>activity (where callback is done)
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="callback"
android:scheme="oauthflow-tumblr" />
</intent-filter>
Image sharing on TUMBLR
public void shareImageOnTumblr(final File imgFile, final String caption,
final Handler handler) {
new Thread(new Runnable() {
#Override
public void run() {
try {
PhotoPost photoPost = client.newPost(client.user()
.getBlogs().get(0).getName(), PhotoPost.class);
if (!caption.isEmpty())
photoPost.setCaption(caption);
photoPost.setPhoto(new Photo(imgFile));
photoPost.save();
Bundle bundle = new Bundle();
Message message = new Message();
bundle.putInt("method",
UploadActivity.SHARED_PHOTO_SUCCESSFULLY);
message.setData(bundle);
handler.sendMessage(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
Video sharing on TUMBLR
public void shareVideoOnTumblr(final File videoFile, final String caption,
final Handler handler) {
new Thread(new Runnable() {
#Override
public void run() {
try {
VideoPost videoPost = client.newPost(client.user()
.getBlogs().get(0).getName(), VideoPost.class);
if (!caption.toString().isEmpty())
videoPost.setCaption(caption.toString());
videoPost.setData(videoFile);
videoPost.save();
Bundle bundle = new Bundle();
Message message = new Message();
bundle.putInt("method",
UploadActivity.SHARED_VIDEO_SUCCESSFULLY);
message.setData(bundle);
handler.sendMessage(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}

Android Socket sending data to WPF application

So i have a registration Android app that in main activity creates a socket connection on create opensocket(). Everything runs perfectly on the first submit, the debugger out put looks great and it sends/recieves data back from my WPF app. Now It goes to a thanks activity which onclick leads back to my mainactivity. Now when i hit submit, it works fine, but is showing its hitting my socket methods twice (only inserts the records once on my WPF app) , and so on as many times i submit. I realize i'm not closing or reusing my socket connection correctly?! I've tried several things, but can't seem to get this to either reuse the same opensocket instance or can't just close and reopen on reload. I'm quite new to android and sockets all together, any help is greatly appreciated!
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
settingsCheck();
openSocket();
sett.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
launchSettings();
}
});
mainLogo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
RefreshMain();
}
});
btn_register.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
tv_errors.setText("");
errorMsg = "";
nameCheck(et_lName.getText().toString(),et_fName.getText().toString());
emailCheck(et_email.getText().toString());
partnerCheck();
mobileCheck(et_mobile.getText().toString());
if (SocketHandler.SocketConnected){
if(errorMsg == ""){
//tv_errors.setText("");
if(checkForSD() == true){
sendRegistrantInfo(et_fName.getText() + "," + et_lName.getText() + "," + et_email.getText() + "," + et_mobile.getText() + "," + et_partEmail.getText() + "," + cb_terms1.isChecked() + "," + cb_terms2.isChecked() );
}
else{
tv_errors.setText("**Please insert an SD Card.");
}
}
else{
//tv_errors.setText(errorMsg);
}
}
else
{
connectionStatus.setText("Connection Error.");
tv_errors.setText("**Connection lost, please try again.");
//openSocket();
}
}
});
}
public void RefreshMain()
{
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
public void launchLogin()
{
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
}//end launchLogin
public void launchSettings()
{
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
}//end launchSettings
public void settingsCheck()
{
SharedPreferences settings = getSharedPreferences("prefs",MODE_PRIVATE);
String currentIP = settings.getString("IPSetting", "");
String currentPort = settings.getString("PORTSetting", "");
currentMem = settings.getString("SDSize", "");
if (currentIP == "" || currentPort == ""){
Intent myIntent = new Intent(this,SettingsActivity.class);
startActivity(myIntent);
}
}//end settingsCheck()
public void launchRingDialog(String id) {
final String idYo = id;
final ProgressDialog ringProgressDialog = ProgressDialog.show(MainActivity.this, "Formatting SD Card","Formatting SD Card, please wait this could take several minutes...", true);
new Thread(new Runnable() {
#Override
public void run() {
try {
fileToSD(idYo);
Thread.sleep(10000);
} catch (Exception e) {
}
ringProgressDialog.dismiss();
}
}).start();
}
public boolean checkForSD()
{
String root = "/storage/removable/sdcard1/";
double memInGigs = round(sizeMatters(root),2);
if(memInGigs >0){
return true;
}
else
{
return false;
}
}
private double sizeMatters(String path)
{
StatFs stat = new StatFs(path);
double availSize = (double)stat.getAvailableBlocks() * (double)stat.getBlockSize();
double ingigs = availSize/ 1073741824;
return ingigs;
}//end sizeMatters()
private void sendRegistrantInfo(String reg){
_sh.sendMessage(reg);
}
private void openSocket(){
_sh = new SocketHandler();
_sh.setSocketHandlerListener(this);
SharedPreferences settings = getSharedPreferences("prefs",MODE_PRIVATE);
String currentIP = settings.getString("IPSetting", "");
String currentPort = settings.getString("PORTSetting", "");
_sh.open(currentIP, currentPort);
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onSocketConnected() {
Log.v(TAG, "onSocketConnected");
connectionStatus.setText("CONNECTED");
}
#Override
public void onSocketData(String msg) {
Log.v(TAG, "onSocketData - " + msg );
int usrID = Integer.parseInt(msg.trim());
if (msg != null & usrID > 0){
launchRingDialog(msg);
Intent intent = new Intent(this, ThanksActivity.class);
startActivity(intent);
}
else if(msg.trim().equals("-2") == true)
{
tv_errors.setText("**This email has already been registered for this event, please click Already Registered button to sign in.");
}
else{
tv_errors.setText("**Error, Please try submitting again.");
errorMsg = "-1";
}
}
#Override
public void onSocketDisconnected() {
Log.v(TAG, "onSocketDisconnected");
connectionStatus.setText("DISCONNECTED");
}
public class SocketHandler {
Socket sc;
public static boolean SocketConnected = false;
private static ClientThread cThread;
public String prefsFile = "prefs";
public String port = "8888";
public String ip = "192.168.1.4";
private String TAG = "SocketHandler";
protected SocketHandlerListener socketHandlerListener;
public interface SocketHandlerListener{
public void onSocketConnected();
public void onSocketData(String msg);
public void onSocketDisconnected();
}
public SocketHandler(){
}
public void setSocketHandlerListener(SocketHandlerListener shl){
socketHandlerListener = shl;
}
public void open(String ip, String port){
this.ip = ip;
this.port = port;
cThread = new ClientThread();
try{
cThread.start();
}catch (Exception ex){
Log.v(TAG, "Error connecting to socket");
}
}
public void close(){
if (cThread != null){
if (cThread.socket != null){
try {
cThread.socket.close();
} catch (Exception e) {
Log.v(TAG, "Error closing socket");
}
cThread.socket = null;
}
}
}
public void sendMessage(String msg){
cThread.sendMessage(msg);
}
public void messageRecieved(String msg){
dispatchSocketData(msg);
}
private void dispatchSocketConnected(){
if (socketHandlerListener != null){
socketHandlerListener.onSocketConnected();
}
}
private void dispatchSocketDisconnected(){
if (socketHandlerListener != null){
socketHandlerListener.onSocketDisconnected();
}
}
private void dispatchSocketData(String msg){
if (socketHandlerListener != null){
socketHandlerListener.onSocketData(msg);
}
}
public class ClientThread extends Thread {
public Socket socket;
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(ip);
Log.v(TAG, "C: Connecting..." + ip + ":" + port);
socket = new Socket(serverAddr, Integer.parseInt(port));
socket.setSoTimeout(0);
socket.setKeepAlive(true);
SocketConnected = true;
handler.post(new Runnable() {
#Override
public void run() {
dispatchSocketConnected();
}
});
// BLOCKING THE THREAD
while (SocketConnected) {
InputStream in = socket.getInputStream();
byte[] buffer = new byte[4096];
int line = in.read(buffer, 0, 4096);
while (line != -1) {
byte[] tempdata = new byte[line];
System.arraycopy(buffer, 0, tempdata, 0, line);
final String data = new String(tempdata);
handler.post(new Runnable() {
#Override
public void run() {
messageRecieved(data);
SocketConnected = false;
}
});
line = in.read(buffer, 0, 4096);
}
// break;
}
socket.close();
Log.v("Socket", "C: Closed.");
handler.post(new Runnable() {
#Override
public void run() {
dispatchSocketDisconnected();
}
});
SocketConnected = false;
} catch (Exception e) {
Log.v("Socket", "C: Error", e);
handler.post(new Runnable() {
#Override
public void run() {
dispatchSocketDisconnected();
}
});
SocketConnected = false;
}
}
Handler handler = new Handler();
public void sendMessage(String msg){
if (socket != null){
if (socket.isConnected()){
PrintWriter out;
try {
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), false);
out.print(msg);
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}

How to call this android bluetooth printing program from phonegap javascript?

i was made a bluetooth printer application (android based) for printing some text using datecs DPP-350 printer device. this program use a datecs external library such as bluetoohconnector and RFComm package. it works nicely, here's the code:
package com.myapp.MobilePrinter1;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.djarum.MobilePrinter1.BluetoothConnector;
import com.datecs.api.card.FinancialCard;
import com.datecs.api.printer.Printer;
import com.datecs.api.printer.PrinterInformation;
import com.datecs.api.printer.ProtocolAdapter;
import com.datecs.api.printer.ProtocolAdapter.Channel;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MobilePrinter1Activity extends Activity {
public static final String CONNECTION_STRING = "connection_string";
private final Handler mHandler = new Handler();
private final Thread mConnectThread = new Thread() {
#Override
public void run() {
String connectionString = "bth://00:01:90:E6:40:52";
showProgress("Connecting");
if (connectionString.startsWith("bth://")) {
String address = connectionString.substring(6);
connectBth(address);
} else {
throw new IllegalArgumentException("Unsupported connection string");
}
dismissProgress();
}
void connectBth(String address) {
//setPrinterInfo(R.drawable.help, address);
try {
mBthConnector = BluetoothConnector.getConnector(MobilePrinter1Activity.this);
mBthConnector.connect(address);
mPrinter = getPrinter(
mBthConnector.getInputStream(),
mBthConnector.getOutputStream());
} catch (IOException e) {
//error(R.drawable.bluetooth, e.getMessage());
return;
}
mPrinterInfo = getPrinterInfo();
}
Printer getPrinter(InputStream in, OutputStream out) throws IOException {
ProtocolAdapter adapter = new ProtocolAdapter(in, out);
Printer printer = null;
if (adapter.isProtocolEnabled()) {
Channel channel = adapter.getChannel(ProtocolAdapter.CHANNEL_PRINTER);
InputStream newIn = channel.getInputStream();
OutputStream newOut = channel.getOutputStream();
printer = new Printer(newIn, newOut);
} else {
printer = new Printer(in, out);
}
return printer;
}
PrinterInformation getPrinterInfo() {
PrinterInformation pi = null;
try {
pi = mPrinter.getInformation();
//setPrinterInfo(R.drawable.printer, pi.getName());
} catch (IOException e) {
e.printStackTrace();
}
return pi;
}
};
private BluetoothConnector mBthConnector;
private Printer mPrinter;
private PrinterInformation mPrinterInfo;
private ProgressDialog mProgressDialog;
private BluetoothConnector mConnector;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
mConnector = BluetoothConnector.getConnector(this);
} catch (IOException e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT);
finish();
}
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
printText();
}
});
findViewById(R.id.button2).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
printBarcode();
}
});
findViewById(R.id.button3).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
printImage();
}
});
}
public void printText() {
new Thread() {
#Override
public void run() {
//showProgress(R.string.printing_text);
doPrintText2();
dismissProgress();
}
}.start();
}
public void printBarcode() {
new Thread() {
#Override
public void run() {
//showProgress(R.string.printing_text);
doPrintBarcode();
dismissProgress();
}
}.start();
}
public void printImage() {
new Thread() {
#Override
public void run() {
//showProgress(R.string.printing_text);
doPrintImage();
dismissProgress();
}
}.start();
}
#Override
protected void onStart() {
super.onStart();
mConnectThread.start();
}
#Override
protected void onStop() {
super.onStop();
if (mBthConnector != null) {
try {
mBthConnector.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void showProgress(final String text) {
mHandler.post(new Runnable() {
#Override
public void run() {
mProgressDialog = ProgressDialog.show(
MobilePrinter1Activity.this,
"Please wait",
text,
true);
}
});
}
private void showProgress(int resId) {
showProgress(getString(resId));
}
private void dismissProgress() {
mHandler.post(new Runnable() {
#Override
public void run() {
mProgressDialog.dismiss();
}
});
}
private void doPrintSelfTest() {
try {
mPrinter.printSelfTest();
} catch (IOException e) {
//error(R.drawable.selftest, getString(R.string.failed_print_self_test) + ". " +
//e.getMessage());
}
}
private void doPrintText2() {
EditText EditText1;
EditText1=(EditText)findViewById(R.id.editText1);
String temp;
try {
mPrinter.reset();
mPrinter.printTaggedText(EditText1.getText().toString());
//mPrinter.printTaggedText("Testing Testing!!");
mPrinter.feedPaper(110);
} catch (IOException e) {
//error(R.drawable.text, getString(R.string.failed_print_text) + ". " +
//e.getMessage());
}
}
private void doPrintBarcode() {
EditText EditText1;
EditText1=(EditText)findViewById(R.id.editText1);
try {
mPrinter.reset();
mPrinter.setBarcode(Printer.ALIGN_CENTER, false, 2, Printer.HRI_BOTH, 100);
mPrinter.printBarcode(Printer.BARCODE_CODE128, EditText1.getText().toString());
mPrinter.feedPaper(38);
mPrinter.feedPaper(110);
} catch (IOException e) {
//error(R.drawable.barcode, getString(R.string.failed_print_barcode) + ". " +
//e.getMessage());
}
}
private void doPrintImage() {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.logo_djarum);
final int width = bitmap.getWidth();
final int height = bitmap.getHeight();
final int[] argb = new int[width * height];
bitmap.getPixels(argb, 0, width, 0, 0, width, height);
try {
mPrinter.reset();
mPrinter.printImage(argb, width, height, Printer.ALIGN_LEFT, true);
mPrinter.feedPaper(110);
} catch (IOException e) {
Toast.makeText(MobilePrinter1Activity.this, e.getMessage(), 1).show();
}
}
private void dialog(final int id, final String title, final String msg) {
mHandler.post(new Runnable() {
#Override
public void run() {
AlertDialog dlg = new AlertDialog.Builder(MobilePrinter1Activity.this)
.setTitle(title)
.setMessage(msg)
.create();
dlg.setIcon(id);
dlg.show();
}
});
}
private void error(final int resIconId, final String message) {
mHandler.post(new Runnable() {
#Override
public void run() {
AlertDialog dlg = new AlertDialog.Builder(MobilePrinter1Activity.this)
.setTitle("Error")
.setMessage(message)
.create();
dlg.setIcon(resIconId);
dlg.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
MobilePrinter1Activity.this.finish();
}
});
dlg.show();
}
});
}
private void setPrinterInfo(final int resIconId, final String text) {
mHandler.post(new Runnable() {
#Override
public void run() {
//((ImageView)findViewById(R.id.icon)).setImageResource(resIconId);
//((TextView)findViewById(R.id.name)).setText(text);
}
});
}
}
the main problems now is how to call this program from phonegap? i've tried using droidGap but it will give me error when i start the printer's thread. has anyone know how to solved this?? many thanks..
I dont think that you can invoke too many APIs from the standard android browser (except some like location, contacts n all), but what is possible is other way round embedding a webview in a native app(which can be your above mentioned thread code) and invoking this code from a Javascript event using JavaScript Interface apis of android platform (which is pretty straight forward).

Categories