android connected with ftp - android

I have download the below code from this website
I can successfully login in filezilla client. But when i typed the same information in this app, it shows (unable to perform action). can anyone help me?
public class MainActivity extends Activity implements OnClickListener {
private static final String TAG = "MainActivity";
private static final String TEMP_FILENAME = "TAGtest.txt";
private Context cntx = null;
private MyFTPClientFunctions ftpclient = null;
private Button btnLoginFtp, btnUploadFile, btnDisconnect, btnExit;
private EditText edtHostName, edtUserName, edtPassword;
private ProgressDialog pd;
private String[] fileList;
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
if (pd != null && pd.isShowing()) {
pd.dismiss();
}
if (msg.what == 0) {
getFTPFileList();
} else if (msg.what == 1) {
showCustomDialog(fileList);
} else if (msg.what == 2) {
Toast.makeText(MainActivity.this, "Uploaded Successfully!",
Toast.LENGTH_LONG).show();
} else if (msg.what == 3) {
Toast.makeText(MainActivity.this, "Disconnected Successfully!",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Unable to Perform Action!",
Toast.LENGTH_LONG).show();
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cntx = this.getBaseContext();
edtHostName = (EditText) findViewById(R.id.edtHostName);
edtUserName = (EditText) findViewById(R.id.edtUserName);
edtPassword = (EditText) findViewById(R.id.edtPassword);
btnLoginFtp = (Button) findViewById(R.id.btnLoginFtp);
btnUploadFile = (Button) findViewById(R.id.btnUploadFile);
btnDisconnect = (Button) findViewById(R.id.btnDisconnectFtp);
btnExit = (Button) findViewById(R.id.btnExit);
btnLoginFtp.setOnClickListener(this);
btnUploadFile.setOnClickListener(this);
btnDisconnect.setOnClickListener(this);
btnExit.setOnClickListener(this);
// Create a temporary file. You can use this to upload
createDummyFile();
ftpclient = new MyFTPClientFunctions();
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnLoginFtp:
if (isOnline(MainActivity.this)) {
connectToFTPAddress();
} else {
Toast.makeText(MainActivity.this,
"Please check your internet connection!",
Toast.LENGTH_LONG).show();
}
break;
case R.id.btnUploadFile:
pd = ProgressDialog.show(MainActivity.this, "", "Uploading...",
true, false);
new Thread(new Runnable() {
public void run() {
boolean status = false;
status = ftpclient.ftpUpload(
Environment.getExternalStorageDirectory()
+ "/TAGFtp/" + TEMP_FILENAME,
TEMP_FILENAME, "/", cntx);
if (status == true) {
Log.d(TAG, "Upload success");
handler.sendEmptyMessage(2);
} else {
Log.d(TAG, "Upload failed");
handler.sendEmptyMessage(-1);
}
}
}).start();
break;
case R.id.btnDisconnectFtp:
pd = ProgressDialog.show(MainActivity.this, "", "Disconnecting...",
true, false);
new Thread(new Runnable() {
public void run() {
ftpclient.ftpDisconnect();
handler.sendEmptyMessage(3);
}
}).start();
break;
case R.id.btnExit:
this.finish();
break;
}
}
private void connectToFTPAddress() {
final String host = edtHostName.getText().toString().trim();
final String username = edtUserName.getText().toString().trim();
final String password = edtPassword.getText().toString().trim();
if (host.length() < 1) {
Toast.makeText(MainActivity.this, "Please Enter Host Address!",
Toast.LENGTH_LONG).show();
} else if (username.length() < 1) {
Toast.makeText(MainActivity.this, "Please Enter User Name!",
Toast.LENGTH_LONG).show();
} else if (password.length() < 1) {
Toast.makeText(MainActivity.this, "Please Enter Password!",
Toast.LENGTH_LONG).show();
} else {
pd = ProgressDialog.show(MainActivity.this, "", "Connecting...",
true, false);
new Thread(new Runnable() {
public void run() {
boolean status = false;
status = ftpclient.ftpConnect(host, username, password, 21);
if (status == true) {
Log.d(TAG, "Connection Success");
handler.sendEmptyMessage(0);
} else {
Log.d(TAG, "Connection failed");
handler.sendEmptyMessage(-1);
}
}
}).start();
}
}
private void getFTPFileList() {
pd = ProgressDialog.show(MainActivity.this, "", "Getting Files...",
true, false);
new Thread(new Runnable() {
#Override
public void run() {
fileList = ftpclient.ftpPrintFilesList("/");
handler.sendEmptyMessage(1);
}
}).start();
}
public void createDummyFile() {
try {
File root = new File(Environment.getExternalStorageDirectory(),
"TAGFtp");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, TEMP_FILENAME);
FileWriter writer = new FileWriter(gpxfile);
writer.append("Hi this is a sample file to upload for android FTP client example from TheAppGuruz!");
writer.flush();
writer.close();
Toast.makeText(this, "Saved : " + gpxfile.getAbsolutePath(),
Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
private boolean isOnline(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
return true;
}
return false;
}
private void showCustomDialog(String[] fileList) {
// custom dialog
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.custom);
dialog.setTitle("/ Directory File List");
TextView tvHeading = (TextView) dialog.findViewById(R.id.tvListHeading);
tvHeading.setText(":: File List ::");
if (fileList != null && fileList.length > 0) {
ListView listView = (ListView) dialog
.findViewById(R.id.lstItemList);
ArrayAdapter<String> fileListAdapter = new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1, fileList);
listView.setAdapter(fileListAdapter);
} else {
tvHeading.setText(":: No Files ::");
}
Button dialogButton = (Button) dialog.findViewById(R.id.btnOK);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
}

Related

Exchanging String between devices over Bluetooth

I am beginner and making my first project on android studio. I want to exchange a unique string between devices over Bluetooth without pairing whenever devices are near. Following is the code I tried but did not work. The code I mention is of scanning part only when click on scan it search for the device and exchange the keys but it is not working.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ON = (Button) findViewById(R.id.button3);
OFF = (Button) findViewById(R.id.button5);
Scan = (Button) findViewById(R.id.search);
myBT = BluetoothAdapter.getDefaultAdapter();
Interaction = (Button) findViewById(R.id.intr);
intentON = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
other = (TextView)findViewById(R.id.textView4);
bluelist = (ListView) findViewById(R.id.btList);
//IntView = (ListView) findViewById(R.id.InList);
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
pAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
bluelist.setAdapter(arrayAdapter);
random = UUID.randomUUID();
getUUID = random.toString();
code = (TextView) findViewById(R.id.textView6);
data = getIntent().getExtras().getString("SomeNumbers");
code.setText(data);
send = (String) code.getText();
checkPermission();
ON.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(myBT.isEnabled())
Toast.makeText(getApplicationContext(), "Bluetooth already Enabled", Toast.LENGTH_SHORT).show();
else
bluetoothOn();
}
});
OFF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bluetoothOff();
}
});
Scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
discover();
}
});
bluelist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//pairDevice(device);
}
});
Interaction.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent getInteractions = new Intent(MainActivity.this, Interactions.class);
//Bundle args = new Bundle();
//args.putSerializable("Exposure", (Serializable)arrayList);
getInteractions.putStringArrayListExtra("Exposure", arrayList);
startActivity(getInteractions);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == BLUETOOTH_REQ_CODE) {
if (resultCode == RESULT_OK) {
Toast.makeText(getApplicationContext(), "Bluetooth is Enabled", Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), "Bluetooth Disabled", Toast.LENGTH_LONG).show();
}
}
}
private void discover(){
if(myBT.isDiscovering()){
myBT.cancelDiscovery();
Toast.makeText(getApplicationContext(),"Discovery stopped",Toast.LENGTH_SHORT).show();
}
else{
if(myBT.isEnabled()) {
arrayAdapter.clear(); // clear items
myBT.startDiscovery();
Toast.makeText(getApplicationContext(), "Discovery started", Toast.LENGTH_SHORT).show();
registerReceiver(receiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
else{
bluetoothOn();
}
}
}
private final BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// add the name to the list
arrayAdapter.add(device.getName() + "\n" + device.getAddress());
arrayAdapter.notifyDataSetChanged();
ServerClass serverClass = new ServerClass();
serverClass.start();
ClientClass clientClass = new ClientClass(pairing);
clientClass.start();
sendReceive.write(send.getBytes());
}
}
};
Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(#NonNull Message msg) {
switch(msg.what)
{
case STATE_LISTENING:
Toast.makeText(getApplicationContext(), "Listening", Toast.LENGTH_SHORT).show();
break;
case STATE_CONNECTING:
Toast.makeText(getApplicationContext(), "Connecting", Toast.LENGTH_SHORT).show();
break;
case STATE_CONNECTED:
Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_SHORT).show();
break;
case STATE_CONNECTION_FAILED:
Toast.makeText(getApplicationContext(), "Connection Failed", Toast.LENGTH_SHORT).show();
break;
case STATE_MESSAGE_RECEIVED:
byte[] readBuff = (byte[]) msg.obj ;
String tempMsg = new String(readBuff,0,msg.arg1);
other.setText(tempMsg);
break;
}
return false;
}
});
private class ServerClass extends Thread
{
private BluetoothServerSocket serverSocket;
public ServerClass()
{
try {
serverSocket = myBT.listenUsingInsecureRfcommWithServiceRecord(App_Name,random);
} catch (IOException e) {
e.printStackTrace();
}
}
public void run()
{
BluetoothSocket socket=null;
while(socket == null)
{
try {
//Message msg = Message.obtain();
//msg.what=
//handler.sendMessage(msg);
socket=serverSocket.accept();
} catch (IOException e) {
e.printStackTrace();
//Message msg = Message.obtain();
//msg.what=
//handler.sendMessage(msg);
}
if(socket != null)
{
//Message msg = Message.obtain();
//msg.what=
//handler.sendMessage(msg);
sendReceive = new SendReceive(socket);
sendReceive.start();
break;
}
}
}
}
private class ClientClass extends Thread
{
private BluetoothDevice device;
private BluetoothSocket socket;
public ClientClass(BluetoothDevice device1)
{
device=device1;
try {
socket = device.createRfcommSocketToServiceRecord(random);
} catch (IOException e) {
e.printStackTrace();
}
}
public void run()
{
try {
socket.connect();
sendReceive = new SendReceive(socket);
sendReceive.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private class SendReceive extends Thread
{
private final BluetoothSocket bluetoothSocket;
private final InputStream inputStream;
private final OutputStream outputStream;
public SendReceive(BluetoothSocket socket)
{
bluetoothSocket=socket;
InputStream tempIn = null;
OutputStream tempOut = null;
try {
tempIn = bluetoothSocket.getInputStream();
tempOut = bluetoothSocket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
inputStream = tempIn;
outputStream = tempOut;
}
public void run()
{
byte[] buffer = new byte[1024];
int bytes;
while(true)
{
try {
bytes = inputStream.read(buffer);
handler.obtainMessage(STATE_MESSAGE_RECEIVED,bytes,-1,buffer).sendToTarget();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void write(byte[] bytes)
{
try {
outputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}

Adding Yandex Translator to Fragment leads to "App Crashes"

I'm Using Yandex Translator in my app, it works great if i'm using Activity, But when i add it to fragment , the app crashes before the launch.
Also no errors shown in the code , like everything is good, what could be the problem :
I looked for similar answers here, but i got nothing, no one had this issue before using fragments.
And here is the code for fragment :
public class FavoritesFragment extends Fragment implements TextToSpeech.OnInitListener{
private TextView header, toText, toLabel, fromLabel;
private ImageView micFrom, volFrom, volTo, reverse;
private EditText fromText;
private CircleButton convertBTN;
private CircleButton convertLayout;
private final int REQ_CODE_SPEECH_INPUT = 100;
private final int SR_CODE = 123;
private String ENGLISH_CONSTANT = "";
private String TURKISH_CONSTANT = "";
private String ENGLISH_CONVERT = "";
private String TURKISH_CONVERT = "";
private String TURKISH_CODE = "";
private String currentFrom = "";
TextToSpeech ttsEnglish, ttsTURKISH;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_favorites, container, false);
setUpInitialConstants();
setUpInteraction();
setUpSpeakingListeners();
setUpListeners();
return v;
}
private void setUpInitialConstants() {
ENGLISH_CONSTANT = ("ENGLISH");
TURKISH_CONSTANT = ("TURKISH");
ENGLISH_CONVERT = ("en") + "-" + ("tr");//"en-zh";
TURKISH_CONVERT = ("tr") + "-" + ("en");
//"zh-en";
TURKISH_CODE = ("tr");
currentFrom = ENGLISH_CONSTANT;
}
private void setUpSpeakingListeners() {
ttsEnglish = new TextToSpeech(getContext().getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
if (status == TextToSpeech.SUCCESS) {
int result = ttsEnglish.setLanguage(Locale.ENGLISH);
if (result == TextToSpeech.LANG_MISSING_DATA ||
result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("error", "This Language is not supported");
} else {
//ConvertTextToSpeech();
}
} else
Log.e("error", "Initilization Failed!");
}
});
ttsTURKISH = new TextToSpeech(getContext().getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
if (status == TextToSpeech.SUCCESS) {
Locale locale = new Locale("tr-TR");
int result = ttsTURKISH.setLanguage(locale);
if (result == TextToSpeech.LANG_MISSING_DATA ||
result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("error", "not supported");
} else {
//ConvertTextToSpeech();
}
} else
Log.e("error", "Initilization Failed!");
}
});
}
#SuppressLint("ClickableViewAccessibility")
private void setUpListeners() {
convertLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(200);
callReverse();
}
});
micFrom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(200);
askSpeechInput(currentFrom);
}
});
volFrom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(200);
ConvertTextToSpeech(currentFrom, fromText.getText().toString());
}
});
volTo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(200);
String currentFromR = reverseCurrentFrom(currentFrom);
ConvertTextToSpeech(currentFromR, toText.getText().toString());
}
});
convertBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(200);
if (currentFrom.equals(ENGLISH_CONSTANT))
translateText(fromText.getText().toString(), ENGLISH_CONVERT);
else
translateText(fromText.getText().toString(), TURKISH_CONVERT);
}
});
toText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(200);
if (copyToClipboard(getContext().getApplicationContext(), toText.getText().toString())) {
if (currentFrom.equals(ENGLISH_CONSTANT)) {
Toast.makeText(getContext().getApplicationContext(), ("copied"), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext().getApplicationContext(), (" copied successfully "), Toast.LENGTH_SHORT).show();
}
}
}
});
fromText.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
fromText.setFocusableInTouchMode(true);
return false;
}
});
}
private String reverseCurrentFrom(String currentFrom) {
if (currentFrom.equals(ENGLISH_CONSTANT)) {
return TURKISH_CONSTANT;
} else return ENGLISH_CONSTANT;
}
private void callReverse() {
if (currentFrom.equals(ENGLISH_CONSTANT)) {
currentFrom = TURKISH_CONSTANT;
//header.setText(getString(R.string.convertHeaderR));
fromLabel.setText(("TURKISH"));
fromText.setHint(("push to talk"));
toLabel.setText(("English"));
toText.setText(("Click translate Button to get English text"));
} else {
currentFrom = ENGLISH_CONSTANT;
//header.setText(getString(R.string.convertHeader));
fromLabel.setText(("English"));
fromText.setHint(("Speak or type text here"));
toLabel.setText(("TURKISH"));
toText.setText(("click to translate"));
}
fromText.setText("");
fromText.setFocusable(false);
}
private void setUpInteraction() {
this.getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
toText = getView().findViewById(R.id.toText);
toLabel = getView().findViewById(R.id.toLabel);
fromLabel = getView().findViewById(R.id.fromLabel);
micFrom = getView().findViewById(R.id.micFrom);
volFrom = getView().findViewById(R.id.volFrom);
volTo = getView().findViewById(R.id.toVol);
convertBTN = getView().findViewById(R.id.convertBTN);
fromText = getView().findViewById(R.id.fromText);
convertLayout = getView().findViewById(R.id.swapLanguage);
fromText.setFocusable(false);
currentFrom = TURKISH_CONSTANT;
callReverse();
}
private void ConvertTextToSpeech(String lang_type, String text) {
if (text == null || "".equals(text)) {
if (lang_type.equals(ENGLISH_CONSTANT)) {
text = ("Content not available");
} else {
text = ("something wrong !");
}
}
if (lang_type.equals(ENGLISH_CONSTANT)) {
ttsEnglish.speak(text, TextToSpeech.QUEUE_FLUSH, null);
} else {
ttsTURKISH.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
private void askSpeechInput(String lang_type) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
if (lang_type.equals(ENGLISH_CONSTANT)) {
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.ENGLISH);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
"Hi speak something");
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} else {
//Specify language
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, TURKISH_CODE);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, TURKISH_CODE);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE, TURKISH_CODE);
intent.putExtra(RecognizerIntent.EXTRA_SUPPORTED_LANGUAGES, TURKISH_CODE);
intent.putExtra(RecognizerIntent.EXTRA_ONLY_RETURN_LANGUAGE_PREFERENCE, TURKISH_CODE);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, TURKISH_CODE);
intent.putExtra(RecognizerIntent.EXTRA_RESULTS, TURKISH_CODE);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, ("speak please"));
startActivityForResult(intent, SR_CODE);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
fromText.setText(result.get(0));
}
break;
}
case SR_CODE: {
if (resultCode == RESULT_OK) {
if (data != null) {
ArrayList<String> nBestList = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
String bestResult = nBestList.get(0);
fromText.setText(bestResult);
}
}
break;
}
}
if (currentFrom.equals(ENGLISH_CONSTANT))
translateText(fromText.getText().toString(), ENGLISH_CONVERT);
else
translateText(fromText.getText().toString(), TURKISH_CONVERT);
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
} else {
Log.e("TTS", "Initialization failed");
}
}
String text_to_return = "";
private String translateText(final String text, final String lang) {
class getQData extends AsyncTask<String, String, String> {
ProgressDialog loading;
String ROOT_URL = "https://translate.yandex.net";
Retrofit adapter = new Retrofit.Builder()
.baseUrl(ROOT_URL)
.addConverterFactory(JacksonConverterFactory.create())
.build();
APICalls api = adapter.create(APICalls.class);
#Override
protected void onPreExecute() {
super.onPreExecute();
showPD();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
#Override
protected String doInBackground(String... params) {
text_to_return = "";
String key = translator_Constants.MY_KEY;
Call<TranslateResponse> call = api.translate(key, text, lang);
call.enqueue(new Callback<TranslateResponse>() {
#Override
public void onResponse(retrofit.Response<TranslateResponse> response, Retrofit retrofit) {
//loading.dismiss();
hidePD();
Log.d("succ", "onResponse:code" + String.valueOf(response.code()));
Log.d("error mesg", String.valueOf(response.message()));
switch (response.code()) {
case 200:
TranslateResponse tr = response.body();
text_to_return = tr.getText().get(0);
toText.setText(text_to_return);
String currentFromR = reverseCurrentFrom(currentFrom);
ConvertTextToSpeech(currentFromR, toText.getText().toString());
break;
default:
if (currentFrom.equals(ENGLISH_CONSTANT))
Toast.makeText(getContext().getApplicationContext(), ("Please Try Again"), Toast.LENGTH_SHORT).show();
else
Toast.makeText(getContext().getApplicationContext(), ("again"), Toast.LENGTH_SHORT).show();
break;
}
}
#Override
public void onFailure(Throwable t) {
pd.dismiss();
Log.d("retro error", t.getMessage());
if (currentFrom.equals(ENGLISH_CONSTANT))
Toast.makeText(getContext().getApplicationContext(), ("Failed to Convert!Check Internet Connection"), Toast.LENGTH_SHORT).show();
else
Toast.makeText(getContext().getApplicationContext(), ("no connexion"), Toast.LENGTH_SHORT).show();
}
});
return text_to_return;
}
}
getQData ru = new getQData();
try {
ru.execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return text_to_return;
}
ProgressDialog pd;
private void showPD() {
pd = new ProgressDialog(getActivity());
if (currentFrom.equals(ENGLISH_CONSTANT)) {
pd.setMessage(("Patience, We are translating…"));
} else {
pd.setMessage(("translating ..."));
}
pd.show();
}
private void hidePD() {
pd.dismiss();
}
public boolean copyToClipboard(Context context, String text) {
try {
int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context
.getSystemService(CLIPBOARD_SERVICE);
clipboard.setText(text);
} else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context
.getSystemService(CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData
.newPlainText("copy", text);
clipboard.setPrimaryClip(clip);
}
return true;
} catch (Exception e) {
return false;
}
}
}
Call setupInteraction() from onViewCreated(), not from onCreateView(). You are trying to use getView(), which will not work until onCreateView() returns.

Unable to send ans receive message from android client using xmpp local server?

I want to build XMPP android client for local server connection, which will able to send text along with live video chat. So initially I am trying to make simple chat application. Using this application I am able to see all the available users but when I try to send a message it does not reach to the server or another client. Can anyone help me to figure out where it the problem?
Chat activity:
public class ChatActivity extends Activity {
private static final int REQUEST_CODE_FOR_GALLERY = 1;
private static final int REQUEST_CODE_FOR_FILEMANAGER = 2;
private static String LOG_TAG = "- Chat Activity -";
private Context context;
private ListView chatListView;
private Button attatchmentButton;
private Button sendButton;
private EditText chatMessageEditText;
private ArrayList<ChatEntry> chatEntries;
private ChatAdapter chatAdapter;
private String fJID, fNickName;
private String mJID, mNickName;
private byte[] fAvatarByte, mAvatarByte;
private Bitmap fAvatarBitmap, mAvatarBitmap;
private XMPPConnection xmppConnection;
private FileTransferManager receiveFileManager;
private FileTransferManager sendFileManager;
private FileTransferListener listener;
private File externalStorageDirectory;
private String fileSrc;
private Handler sHandler, rHandler;
private Thread sThread;
private File rfile;
private LinearLayout layoutReceivingFile;
private LinearLayout layoutSendinfFile;
private ProgressBar rProgressBar;
private ProgressBar sProgressBar;
private ChatManager chatManager;
private Chat chat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_chat);
// Context
context = this;
// View matching
chatListView = (ListView) findViewById(R.id.chat_message_listview);
attatchmentButton = (Button) findViewById(R.id.chat_attatchment_button);
sendButton = (Button) findViewById(R.id.chat_send_button);
chatMessageEditText = (EditText) findViewById(R.id.chat_message_edit_text);
layoutReceivingFile = (LinearLayout) findViewById(R.id.chat_file_transfer_receive_layout);
layoutSendinfFile = (LinearLayout) findViewById(R.id.chat_file_transfer_send_layout);
rProgressBar = (ProgressBar) findViewById(R.id.chat_receive_file_progress_bar);
sProgressBar = (ProgressBar) findViewById(R.id.chat_send_file_progress_bar);
// Event for attachment button
attatchmentButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("File attachment");
builder.setMessage("Choose your file type.");
builder.setNegativeButton("Picture", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, REQUEST_CODE_FOR_GALLERY);
}
});
builder.setPositiveButton("File", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(ChatActivity.this, FilePickerActivity.class);
ArrayList<String> extensions = new ArrayList<String>();
extensions.add(".png");
extensions.add(".jpg");
extensions.add(".gif");
extensions.add(".tif");
extensions.add(".bmp");
extensions.add(".doc");
extensions.add(".docx");
extensions.add(".ppt");
extensions.add(".pptx");
extensions.add(".xls");
extensions.add(".xlsx");
extensions.add(".pdf");
extensions.add(".zip");
extensions.add(".rar");
intent.putExtra(FilePickerActivity.EXTRA_ACCEPTED_FILE_EXTENSIONS, extensions);
startActivityForResult(intent, REQUEST_CODE_FOR_FILEMANAGER);
}
});
builder.setCancelable(true);
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
});
// Event for send message button
sendButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
String message = chatMessageEditText.getText().toString();
if ( message.trim().length() == 0 ) {
Toast.makeText(context, "Please fill up some text.", Toast.LENGTH_SHORT).show();
} else {
try {
chat.sendMessage(message);
chatMessageEditText.setText(null);
Log.d(LOG_TAG, "Trying to send message 1");
Toast.makeText(context, "trying to send" +message.toString(), Toast.LENGTH_LONG).show();
ChatEntry chatEntry = new ChatEntry();
chatEntry.setAttachedFile(false);
chatEntry.setFilePath(null);
chatEntry.setSenderJID(mJID);
chatEntry.setReceiverJID(fJID);
chatEntry.setSenderAvatarBitmap(mAvatarBitmap);
chatEntry.setWhen(System.currentTimeMillis());
chatEntry.setMessage(message);
Log.d(LOG_TAG, "Trying to send message 2");
chatEntries.add(chatEntry);
chatAdapter.setData(chatEntries);
chatAdapter.notifyDataSetChanged();
chatListView.setSelection(chatEntries.size()-1);
Log.d(LOG_TAG, "Trying to send message 3");
} catch (XMPPException e) {
Log.e(LOG_TAG, "Unable to send message: "+e.getMessage());
}
}
}
});
// Event for chat list view
chatListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapterView, View view, int position, long which) {
if ( chatEntries.get(position).isAttachedFile() ) {
File file = new File(chatEntries.get(position).getFilePath());
if ( isImageFile(file) ) {
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "image/*");
startActivity(intent);
} else {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.fromFile(file));
startActivity(intent);
}
}
}
});
// Extras
Bundle bundle = getIntent().getExtras();
if ( bundle == null ) {
ChatActivity.this.finish();
} else {
// Get active connection
xmppConnection = MainActivity.getXMPPConnection();
if ( xmppConnection == null ) {
ChatActivity.this.finish();
} else {
// For BEEM
FileTransferNegotiator.IBB_ONLY = true;
// -- END OF FOR BEEM
// Enable Server Discovery Manager
ServiceDiscoveryManager sdm = new ServiceDiscoveryManager(xmppConnection);
// sdm.addFeature("http://jabber.org/protocol/ibb");
// FOR BEEM
sdm.addFeature("http://jabber.org/protocol/disco#info");
sdm.addFeature("http://jabber.org/protocol/disco#item");
sdm.addFeature("jabber:iq:privacy");
// -- END OF FOR BEEM
// Receive data from extras
fJID = bundle.getString("fJID");
fJID += "/"+ApplicationSetting.SERVER_RESOURCE;
fNickName = bundle.getString("fNickName");
fAvatarByte = bundle.getByteArray("fAvatarByte");
fAvatarBitmap = BitmapUtility.convertByteArrayToBitmap(fAvatarByte);
mJID = bundle.getString("mJID");
mNickName = bundle.getString("mNickName");
mAvatarByte = bundle.getByteArray("mAvatarByte");
mAvatarBitmap = BitmapUtility.convertByteArrayToBitmap(mAvatarByte);
Toast.makeText(context, "fjid is "+fJID + "mjid is "+mJID, Toast.LENGTH_LONG).show();
// Initialize
chatMessageEditText.setSingleLine(true);
chatEntries = new ArrayList<ChatEntry>();
chatAdapter = new ChatAdapter(context, chatEntries, mJID);
chatListView.setAdapter(chatAdapter);
chatListView.setDivider(null);
fileSrc = null;
rProgressBar.setMax(100);
sProgressBar.setMax(100);
sProgressBar.setClickable(false);
rProgressBar.setClickable(false);
layoutReceivingFile.setVisibility(View.GONE);
layoutSendinfFile.setVisibility(View.GONE);
// Set title for this activity
setTitle("Chat with "+fNickName);
Log.i(LOG_TAG, mNickName+" chat with "+fNickName);
// Create Chat Manager
chatManager = xmppConnection.getChatManager();
// Add Chat Listener
chatManager.addChatListener(new ChatManagerListener() {
public void chatCreated(Chat chat, boolean isCreated) {
Toast.makeText(context, "Chat was created.", Toast.LENGTH_LONG).show();
Log.i(LOG_TAG, "Chat was created.");
}
});
// Create chat channel with friend
final Handler chatHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch ( msg.what ) {
case 1:
org.jivesoftware.smack.packet.Message chatMessage;
chatMessage = (org.jivesoftware.smack.packet.Message) msg.obj;
Toast.makeText(context, "Chat message." +msg.toString(), Toast.LENGTH_LONG).show();
ChatEntry chatEntry = new ChatEntry();
chatEntry.setAttachedFile(false);
chatEntry.setFilePath(null);
chatEntry.setSenderJID(fJID);
chatEntry.setReceiverJID(mJID);
chatEntry.setSenderAvatarBitmap(fAvatarBitmap);
chatEntry.setWhen(System.currentTimeMillis());
chatEntry.setMessage(chatMessage.getBody());
chatEntries.add(chatEntry);
chatAdapter.setData(chatEntries);
chatAdapter.notifyDataSetChanged();
chatListView.setSelection(chatEntries.size()-1);
break;
}
}
};
chat = chatManager.createChat(fJID, new MessageListener() {
public void processMessage(Chat chat, final org.jivesoftware.smack.packet.Message chatMessage) {
Toast.makeText(context, "chatManager.createChat(fJID, new MessageListener() " , Toast.LENGTH_LONG).show();
if ( chatMessage.getBody() != null ) {
new Thread() {
public void run() {
Message msg = new Message();
msg.what = 1;
msg.obj = chatMessage;
Toast.makeText(context, "Chat message.before chathandler" +msg.toString(), Toast.LENGTH_LONG).show();
chatHandler.sendMessage(msg);
};
}.start();
Log.i(LOG_TAG, "Received message from: "+chatMessage.getFrom()+": "+chatMessage.getBody());
}
}
});
// Setup file transfer manager
receiveFileManager = new FileTransferManager(xmppConnection);
sendFileManager = new FileTransferManager(xmppConnection);
// Setup default saving directory ('mychat' on sd card)
externalStorageDirectory = new File(Environment.getExternalStorageDirectory(), "mychat");
// Setup handler for receive file listener
rHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch ( msg.what ) {
case 0:
// Finish with error
layoutReceivingFile.setVisibility(View.GONE);
Toast.makeText(context, "Unable to receive file.", Toast.LENGTH_LONG).show();
break;
case 1:
// Finish with complete
layoutReceivingFile.setVisibility(View.GONE);
Toast.makeText(context, "You have received new file.", Toast.LENGTH_LONG).show();
ChatEntry chatEntry = new ChatEntry();
chatEntry.setAttachedFile(true);
chatEntry.setFilePath(rfile.getAbsolutePath());
chatEntry.setSenderJID(fJID);
chatEntry.setReceiverJID(mJID);
chatEntry.setSenderAvatarBitmap(fAvatarBitmap);
chatEntry.setWhen(System.currentTimeMillis());
chatEntry.setMessage("You just received an attachment.");
chatEntries.add(chatEntry);
chatAdapter.setData(chatEntries);
chatAdapter.notifyDataSetChanged();
chatListView.setSelection(chatEntries.size()-1);
break;
case 2:
// Streaming
layoutReceivingFile.setVisibility(View.VISIBLE);
break;
}
}
};
// Setup receive file listener
listener = new FileTransferListener() {
public void fileTransferRequest(final FileTransferRequest request) {
Log.i(LOG_TAG, "Receive file coming");
new Thread() {
public void run() {
IncomingFileTransfer transfer = request.accept();
rfile = new File(externalStorageDirectory, transfer.getFileName());
try {
transfer.recieveFile(rfile);
Log.i(LOG_TAG, "Start receive file.");
while ( !transfer.isDone() ) {
try {
sleep(1000);
int percent = (int)(transfer.getProgress()*100);
if ( percent == 100 ) {
rProgressBar.setProgress(0);
} else {
rProgressBar.setProgress(percent);
}
Log.i(LOG_TAG, "Receiving file: "+percent+" %");
rHandler.sendEmptyMessage(2);
} catch ( InterruptedException e ) {
e.printStackTrace();
Log.e(LOG_TAG, "Receiving thread was interrupoted: "+e.getMessage());
}
}
if ( transfer.getStatus().equals(Status.complete) ) {
rHandler.sendEmptyMessage(1);
Log.i(LOG_TAG, "Receive file Completed.");
} else if ( transfer.getStatus().equals(Status.cancelled) ) {
rHandler.sendEmptyMessage(0);
Log.e(LOG_TAG, "Receive file Cancelled.");
} else if ( transfer.getStatus().equals(Status.error) ) {
rHandler.sendEmptyMessage(0);
Log.e(LOG_TAG, "Receive file Error.");
} else if ( transfer.getStatus().equals(Status.refused) ) {
rHandler.sendEmptyMessage(0);
Log.e(LOG_TAG, "Receive file Refused.");
}
} catch ( Exception e ) {
Log.e(LOG_TAG, "Unable to receive file: "+e.getMessage());
}
};
}.start();
}
};
// Add receive file listener
receiveFileManager.addFileTransferListener(listener);
}
}
}
// Send file
public void sendFile(final File file) {
sHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch ( msg.what ) {
case 0:
// Finish with error
layoutSendinfFile.setVisibility(View.GONE);
Toast.makeText(context, "Unable to send file.", Toast.LENGTH_LONG).show();
break;
case 1:
// Finish with complete
layoutSendinfFile.setVisibility(View.GONE);
Toast.makeText(context, "Your file has been sent.", Toast.LENGTH_LONG).show();
ChatEntry chatEntry = new ChatEntry();
chatEntry.setAttachedFile(true);
chatEntry.setFilePath(fileSrc);
chatEntry.setSenderJID(mJID);
chatEntry.setReceiverJID(fJID);
chatEntry.setSenderAvatarBitmap(mAvatarBitmap);
chatEntry.setWhen(System.currentTimeMillis());
chatEntry.setMessage("Your attachment has been sent.");
chatEntries.add(chatEntry);
chatAdapter.setData(chatEntries);
chatAdapter.notifyDataSetChanged();
chatListView.setSelection(chatEntries.size()-1);
break;
case 2:
// Streaming
layoutSendinfFile.setVisibility(View.VISIBLE);
break;
}
}
};
sThread = new Thread() {
#Override
public void run() {
Log.i(LOG_TAG, "Send file coming");
OutgoingFileTransfer transfer = sendFileManager.createOutgoingFileTransfer(fJID);
try {
transfer.sendFile(file, "iChat-attachment-file");
Log.i(LOG_TAG, "Starting send file");
while ( !transfer.isDone() ) {
try {
sleep(1000);
int percent = (int)(transfer.getProgress()*100);
if ( percent == 100 ) {
sProgressBar.setProgress(0);
} else {
sProgressBar.setProgress(percent);
}
Log.i(LOG_TAG, "Sending file: "+percent+" %");
sHandler.sendEmptyMessage(2);
} catch (InterruptedException e) {
e.printStackTrace();
Log.e(LOG_TAG, "Send file thread was interrupted: "+e.getMessage());
}
}
if ( transfer.getStatus().equals(Status.complete) ) {
sHandler.sendEmptyMessage(1);
Log.i(LOG_TAG, "Send file is completed");
} else {
sHandler.sendEmptyMessage(0);
Log.e(LOG_TAG, "Send file is failed");
}
} catch (XMPPException e) {
Log.e(LOG_TAG, "Unable to send file: "+e.getMessage());
}
}
};
sThread.start();
}
#Override
protected void onActivityResult(int requestCode, int resultcode, Intent intent) {
super.onActivityResult(requestCode, resultcode, intent);
if (requestCode == REQUEST_CODE_FOR_GALLERY) {
if (intent != null) {
Cursor cursor = getContentResolver().query(intent.getData(), null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(ImageColumns.DATA);
fileSrc = cursor.getString(idx);
File file = new File(fileSrc);
if ( file.exists() ) {
sendFile(file);
} else {
Toast.makeText(context, "Image was not found, please try again.", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(context, "Cancelled", Toast.LENGTH_SHORT).show();
}
} else if (requestCode == REQUEST_CODE_FOR_FILEMANAGER) {
if ( resultcode == RESULT_OK ) {
if( intent.hasExtra(FilePickerActivity.EXTRA_FILE_PATH) ) {
File file = new File(intent.getStringExtra(FilePickerActivity.EXTRA_FILE_PATH));
// Set the file path text view
if ( file.exists() && isAllowedFileExtension(file) ) {
sendFile(file);
} else {
Toast.makeText(context, "This file is not allowed, please choose another file.", Toast.LENGTH_LONG).show();
}
}
} else {
Toast.makeText(context, "Cancelled", Toast.LENGTH_SHORT).show();
}
}
}
public boolean isAllowedFileExtension(File file) {
boolean result = false;
String filename = file.getName();
int length = filename.length();
int correctPosition = 0;
String ext = "";
for ( int i = length-1; i > 0; i-- ) {
if ( filename.charAt(i) == '.' ) {
correctPosition = i;
break;
}
}
if ( correctPosition == 0 ) {
Toast.makeText(context, "This file is invalid, please choose another file.", Toast.LENGTH_LONG).show();
} else {
for ( int i = correctPosition+1; i < length; i++ ) {
ext += filename.charAt(i);
}
if ( ext.trim().length() == 0 ) {
Toast.makeText(context, "This file is invalid, please choose another file.", Toast.LENGTH_LONG).show();
} else {
boolean isAllowedExtension = false;
String[] allowedExtension = new String[] { "png", "jpg", "gif", "tif", "bmp", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "pdf", "zip", "rar" };
for ( int i = 0; i < allowedExtension.length; i++ ) {
if ( ext.equalsIgnoreCase(allowedExtension[i]) ) {
isAllowedExtension = true;
}
}
if ( isAllowedExtension ) {
result = true;
}
}
}
return result;
}
public boolean isImageFile(File file) {
boolean result = false;
String filename = file.getName();
int length = filename.length();
int correctPosition = 0;
String ext = "";
for ( int i = length-1; i > 0; i-- ) {
if ( filename.charAt(i) == '.' ) {
correctPosition = i;
break;
}
}
if ( correctPosition == 0 ) {
Toast.makeText(context, "This file is invalid, please choose another file.", Toast.LENGTH_LONG).show();
} else {
for ( int i = correctPosition+1; i < length; i++ ) {
ext += filename.charAt(i);
}
if ( ext.trim().length() == 0 ) {
Toast.makeText(context, "This file is invalid, please choose another file.", Toast.LENGTH_LONG).show();
} else {
boolean isAllowedExtension = false;
String[] allowedExtension = new String[] { "png", "jpg", "gif", "tif", "bmp" };
for ( int i = 0; i < allowedExtension.length; i++ ) {
if ( ext.equalsIgnoreCase(allowedExtension[i]) ) {
isAllowedExtension = true;
}
}
if ( isAllowedExtension ) {
result = true;
}
}
}
return result;
}

Print image via bluetooth printer AGPtEK SC28

I have some problem with printing image to AGPtEK 58mm Mini Bluetooth Pocket POS Thermal Receipt Printer. I am trying to convert webview content into image (this is working fine) and after that I want to print it with this printer but it prints only solid black background. Here is my code:
public class PrintDemo extends Activity {
private static final int REQUEST_ENABLE_BT = 2;
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int PERMISSIONS_REQUEST_BLUETOOTH = 1;
private static final String TAG_REQUEST_PERMISSION = "Request permission";
private static final int PERMISSIONS_REQUEST_INTERNET = 0;
private static final int PERMISSIONS_REQUEST_BT_ADMIN = 2;
private static final int PERMISSIONS_REQUEST_LOCATION = 3;
private static final String WEB_SITE = "Remembered Web Site";
private static final String IS_CHECKED = "Check box";
#Bind(R.id.btn_search)
Button btnSearch;
#Bind(R.id.btn_print)
Button btnSendDraw;
#Bind(R.id.btn_open)
Button btnSend;
#Bind(R.id.btn_close)
Button btnClose;
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case BluetoothService.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case BluetoothService.STATE_CONNECTED:
Toast.makeText(getApplicationContext(), "Connect successful",
Toast.LENGTH_SHORT).show();
btnClose.setEnabled(true);
btnSend.setEnabled(true);
btnSendDraw.setEnabled(true);
break;
case BluetoothService.STATE_CONNECTING:
Log.d("State", "Connecting...");
break;
case BluetoothService.STATE_LISTEN:
case BluetoothService.STATE_NONE:
Log.d("State", "Not found");
break;
}
break;
case BluetoothService.MESSAGE_CONNECTION_LOST:
Toast.makeText(getApplicationContext(), "Device connection was lost",
Toast.LENGTH_SHORT).show();
btnClose.setEnabled(false);
btnSend.setEnabled(true);
btnSendDraw.setEnabled(false);
break;
case BluetoothService.MESSAGE_UNABLE_CONNECT:
Toast.makeText(getApplicationContext(), "Unable to connect device",
Toast.LENGTH_SHORT).show();
break;
}
}
};
String path;
File dir;
File file;
#Bind(R.id.check_box)
CheckBox checkBox;
#Bind(R.id.txt_content)
EditText edtContext;
#Bind(R.id.web_view)
WebView webView;
BluetoothService mService;
BluetoothDevice con_dev;
private SharedPreferences sharedPref;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fabric.with(this, new Crashlytics());
setContentView(R.layout.main);
ButterKnife.bind(this);
mService = new BluetoothService(this, mHandler);
if (!mService.isAvailable()) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
}
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDefaultTextEncodingName("utf-8");
webView.setWebViewClient(new WebViewClient() {
#SuppressLint("SdCardPath")
#Override
public void onPageFinished(final WebView view, String url) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
siteToImage(view);
}
}, 5000);
}
});
sharedPref = this.getPreferences(Context.MODE_PRIVATE);
checkPermissions();
}
private void siteToImage(WebView view) {
Picture picture = view.capturePicture();
Bitmap b = Bitmap.createBitmap(
picture.getWidth(), picture.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
picture.draw(c);
FileOutputStream fos;
try {
path = Environment.getExternalStorageDirectory().toString();
dir = new File(path, "/PrintDemo/media/img/");
if (!dir.isDirectory()) {
dir.mkdirs();
}
String arquivo = "darf_" + System.currentTimeMillis() + ".jpg";
file = new File(dir, arquivo);
fos = new FileOutputStream(file);
String imagePath = file.getAbsolutePath();
//scan the image so show up in album
MediaScannerConnection.scanFile(PrintDemo.this, new String[]{imagePath},
null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
if (fos != null) {
b.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void setRememberedWeb() {
if (checkBox.isChecked()) {
String rememberedWeb = sharedPref.getString(WEB_SITE, "");
if (!rememberedWeb.equals("")) {
edtContext.setText(rememberedWeb);
}
}
}
#Override
protected void onPause() {
super.onPause();
saveState(checkBox.isChecked());
}
#Override
protected void onResume() {
super.onResume();
checkBox.setChecked(load());
setRememberedWeb();
}
private void saveState(boolean isChecked) {
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean(IS_CHECKED, isChecked);
if (isChecked) {
editor.putString(WEB_SITE, edtContext.getText().toString());
} else {
editor.putString(WEB_SITE, getString(R.string.txt_content));
}
editor.apply();
}
private boolean load() {
return sharedPref.getBoolean(IS_CHECKED, false);
}
private boolean checkPermissions() {
int permissionCheck =
ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH);
int permissionInternet =
ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET);
int permissionBTAdmin =
ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADMIN);
int permissionLocation =
ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION);
if (permissionCheck == PackageManager.PERMISSION_DENIED) {
edtContext.setText(R.string.no_bluetooth_permissions);
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.BLUETOOTH)) {
Toast.makeText(PrintDemo.this, TAG_REQUEST_PERMISSION, Toast.LENGTH_SHORT).show();
} else {
requestBTPermission();
}
return false;
} else if (permissionInternet == PackageManager.PERMISSION_DENIED) {
edtContext.setText(R.string.no_internet_permissions);
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.INTERNET)) {
Toast.makeText(PrintDemo.this, TAG_REQUEST_PERMISSION, Toast.LENGTH_SHORT).show();
} else {
requestInternetPermission();
}
return false;
} else if (permissionBTAdmin == PackageManager.PERMISSION_DENIED) {
edtContext.setText(R.string.no_bt_admin_permissions);
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.INTERNET)) {
Toast.makeText(PrintDemo.this, TAG_REQUEST_PERMISSION, Toast.LENGTH_SHORT).show();
} else {
requestBTAdminPermission();
}
return false;
} else if (permissionLocation == PackageManager.PERMISSION_DENIED) {
edtContext.setText(R.string.no_location_permissions);
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_COARSE_LOCATION)) {
Toast.makeText(PrintDemo.this, TAG_REQUEST_PERMISSION, Toast.LENGTH_SHORT).show();
} else {
requestLocationPermission();
}
return false;
} else {
return true;
}
}
private void requestLocationPermission() {
ActivityCompat
.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
PERMISSIONS_REQUEST_LOCATION);
}
private void requestBTAdminPermission() {
ActivityCompat
.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH_ADMIN},
PERMISSIONS_REQUEST_BT_ADMIN);
}
private void requestInternetPermission() {
ActivityCompat
.requestPermissions(this, new String[]{Manifest.permission.INTERNET},
PERMISSIONS_REQUEST_INTERNET);
}
private void requestBTPermission() {
ActivityCompat
.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH},
PERMISSIONS_REQUEST_BLUETOOTH);
}
#Override
public void onStart() {
super.onStart();
if (!mService.isBTopen()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}
try {
btnSendDraw = (Button) this.findViewById(R.id.btn_print);
btnSendDraw.setOnClickListener(new ClickEvent());
btnSearch = (Button) this.findViewById(R.id.btn_search);
btnSearch.setOnClickListener(new ClickEvent());
btnSend = (Button) this.findViewById(R.id.btn_open);
btnSend.setOnClickListener(new ClickEvent());
btnClose = (Button) this.findViewById(R.id.btn_close);
btnClose.setOnClickListener(new ClickEvent());
edtContext = (EditText) findViewById(R.id.txt_content);
btnClose.setEnabled(false);
btnSend.setEnabled(true);
btnSendDraw.setEnabled(false);
} catch (Exception ex) {
Log.e("TAG", ex.getMessage());
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mService != null)
mService.stop();
mService = null;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_ENABLE_BT:
if (resultCode == Activity.RESULT_OK) {
Toast.makeText(this, "Bluetooth open successful", Toast.LENGTH_LONG).show();
} else {
finish();
}
break;
case REQUEST_CONNECT_DEVICE:
if (resultCode == Activity.RESULT_OK) {
String address = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
con_dev = mService.getDevByMac(address);
mService.connect(con_dev);
}
break;
}
}
#SuppressLint("SdCardPath")
private void printImage() {
byte[] sendData;
PrintPic pg = new PrintPic();
pg.initCanvas(384);
pg.initPaint();
pg.drawImage(0, 0, file.getPath());
sendData = pg.printDraw();
mService.write(sendData);
}
public void downloadContent() {
if (!edtContext.getText().toString().equals("") && !edtContext.getText().toString().equals("https://")) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(edtContext.getText().toString())
.build();
HttpService service = retrofit.create(HttpService.class);
Call<ResponseBody> result = service.getContent();
result.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Response<ResponseBody> response) {
try {
if (response.body() != null) {
String summary = response.body().string();
webView.loadData(summary, "text/html; charset=utf-8", null);
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable t) {
}
});
}
}
public interface HttpService {
#GET("/")
Call<ResponseBody> getContent();
}
class ClickEvent implements View.OnClickListener {
public void onClick(View v) {
if (v == btnSearch) {
Intent serverIntent = new Intent(PrintDemo.this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
} else if (v == btnSend) {
downloadContent();
} else if (v == btnClose) {
mService.stop();
} else if (v == btnSendDraw) {
printImage();
}
}
}
}
The result is almost what I want you can see by yourself, but the printed image is not clear:
I fixed it guys, this was the problem, the method siteToImage(). Here are the changes I hope it will helps someone:
private void siteToImage() {
webView.measure(View.MeasureSpec.makeMeasureSpec(
View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
webView.setDrawingCacheEnabled(true);
webView.buildDrawingCache();
Bitmap b = Bitmap.createBitmap(webView.getMeasuredWidth(),
webView.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
Paint paint = new Paint();
int iHeight = b.getHeight();
c.drawBitmap(b, 0, iHeight, paint);
webView.draw(c);
FileOutputStream fos;
try {
path = Environment.getExternalStorageDirectory().toString();
dir = new File(path, "/PrintDemo/media/img/");
if (!dir.isDirectory()) {
dir.mkdirs();
}
String arquivo = "darf_" + System.currentTimeMillis() + ".jpg";
file = new File(dir, arquivo);
fos = new FileOutputStream(file);
String imagePath = file.getAbsolutePath();
//scan the image so show up in album
MediaScannerConnection.scanFile(PrintDemo.this, new String[]{imagePath},
null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
b.compress(Bitmap.CompressFormat.PNG, 50, fos);
fos.flush();
fos.close();
b.recycle();
} catch (Exception e) {
e.printStackTrace();
}
}

android textview does not show after setting visible from another thread

I am having problems making my TextViews visible from another thread using the method showDisclaimer(). I have used runOnUiThread() to set the visibility of my TextViews. Basically, I want to show these views after importing the csv to the database. Can you take a look and see what I missed?
public class MainActivity extends Activity {
final static int INDEX_ACCTTYPE = 0;
final static int INDEX_ECN = 1;
final static int INDEX_TLN = 2;
final static int INDEX_SIN = 3;
final static int INDEX_MOBILE = 4;
final static int INDEX_CITY = 5;
final static int INDEX_START_DATE = 6;
final static int INDEX_START_TIME = 7;
final static int INDEX_END_DATE = 8;
final static int INDEX_END_TIME = 9;
final static int INDEX_REASON = 10;
final static int INDEX_DETAILS = 11;
DatabaseHandler db;
String str;
ProgressDialog pd;
final private String csvFile = "http://www.meralco.com.ph/pdf/pms/pms_test.csv";
final private String uploadDateFile = "http://www.meralco.com.ph/pdf/pms/UploadDate_test.txt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView homeText1 = (TextView) findViewById(R.id.home_text1);
TextView homeText2 = (TextView) findViewById(R.id.home_text2);
TextView homeText3 = (TextView) findViewById(R.id.home_text3);
TextView homeText4 = (TextView) findViewById(R.id.home_text4);
homeText1.setVisibility(View.INVISIBLE);
homeText2.setVisibility(View.INVISIBLE);
homeText3.setVisibility(View.INVISIBLE);
homeText4.setVisibility(View.INVISIBLE);
//db = new DatabaseHandler(MainActivity.this);
if(dbExists()){
db = new DatabaseHandler(MainActivity.this);
Log.d("Count", "" + db.count());
if(!uploadDateEqualsDateInFile())
promptOptionalUpdate("There is a new schedule");
showDisclaimer();
Log.i("oncreate", "finished!");
return;
}
promptRequiredUpdate("Schedule not updated");
//showDisclaimer();
Log.i("oncreate", "finished!");
}
public void promptOptionalUpdate(String Message) {
AlertDialog.Builder builder = new AlertDialog.Builder(
this);
builder.setMessage(Message)
.setCancelable(false)
.setPositiveButton("Update Now",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.d("SHOW ALERT -->!", "update");
dropOldSchedule();
triggerDownload();
dialog.cancel();
}
})
.setNegativeButton("Later",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.d("SHOW ALERT -->!", "cancel");
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void dropOldSchedule(){
//TODO drop old schedule
}
public void triggerDownload() {
if (!checkInternet()) {
showAlert("An internet connection is required to perform an update, please check that you are connected to the internet");
return;
}
if(pd!=null && pd.isShowing()) pd.dismiss();
pd = ProgressDialog.show(this, "Downloading schedule",
"This may take a few minutes...", true, false);
Thread thread = new Thread(new Runnable() {
public void run() {
db = new DatabaseHandler(MainActivity.this);
db.beginTransaction();
try {
URL myURL = new URL(csvFile);
BufferedReader so = new BufferedReader(new InputStreamReader(myURL.openStream()));
while (true) {
String output = so.readLine();
if (output != null) {
String[] sched = output.split(",");
try {
db.addRow(sched[INDEX_SIN], sched[INDEX_CITY],
sched[INDEX_START_DATE], sched[INDEX_START_TIME],
sched[INDEX_END_DATE], sched[INDEX_END_TIME],
sched[INDEX_DETAILS], sched[INDEX_REASON]);
} catch (IndexOutOfBoundsException e) {
db.addRow(sched[INDEX_SIN], sched[INDEX_CITY],
sched[INDEX_START_DATE], sched[INDEX_START_TIME],
sched[INDEX_END_DATE], sched[INDEX_END_TIME],
"", sched[INDEX_REASON]);
e.printStackTrace();
}
}
else {
break;
}
}
so.close();
} catch (MalformedURLException e) {
e.printStackTrace();
db.endTransaction();
} catch (IOException e) {
e.printStackTrace();
db.endTransaction();
}
Log.d("Count", ""+db.count());
db.setTransactionSuccessful();
db.endTransaction();
runOnUiThread(new Runnable() {
public void run() {
while (!pd.isShowing());
getUploadDate();
writeUploadDateInTextFile();
showDisclaimer();
pd.dismiss();
}
});
}
});
thread.start();
//while(thread.isAlive());
Log.d("triggerDownload", "thread died, finished dl. showing disclaimer...");
}
public void getUploadDate() {
Log.d("getUploadDate", "getting upload date of schedule");
if(pd!=null && pd.isShowing()) pd.dismiss();
pd = ProgressDialog.show(this, "Getting upload date",
"This may take a few minutes...", true, false);
Thread thread = new Thread(new Runnable() {
public void run() {
try {
URL myURL = new URL(uploadDateFile);
BufferedReader so = new BufferedReader(new InputStreamReader(myURL.openStream()));
while (true) {
String output = so.readLine();
if (output != null) {
str = output;
}
else {
break;
}
}
so.close();
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
public void run() {
while (!pd.isShowing());
pd.dismiss();
}
});
}
});
thread.start();
while (thread.isAlive());
Log.d("getUploadDate","thread died, upload date="+str);
}
public void writeUploadDateInTextFile() {
Log.d("writeUploadDateTextFile", "writing:"+str);
try {
OutputStreamWriter out = new OutputStreamWriter(openFileOutput(
"update.txt", 0));
out.write(str);
out.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
public void showDisclaimer() {
Log.d("ShowDisclaimer", "showing disclaimer");
TextView homeText1x = (TextView) findViewById(R.id.home_text1);
TextView homeText2x = (TextView) findViewById(R.id.home_text2);
TextView homeText3x = (TextView) findViewById(R.id.home_text3);
TextView homeText4x = (TextView) findViewById(R.id.home_text4);
homeText3x
.setText("You may view the schedule of pre-arranged power interruptions by clicking any of these buttons : SIN, City or Date. " +
"The schedule has been updated as of " + str
+ ". Meralco is exerting all efforts to restore electric service as scheduled." +
" The schedule, however, may change without further notice. For verification, follow-ups, or " +
"latest updates, please contact our CALL CENTER through telephone nos. 16211, " +
"fax nos. 1622-8554/1622-8556 or email address callcenter.tech.assist#meralco.com.ph.");
homeText1x.setVisibility(View.VISIBLE);
homeText2x.setVisibility(View.VISIBLE);
homeText3x.setVisibility(View.VISIBLE);
homeText4x.setVisibility(View.VISIBLE);
Log.d("ShowDisclaimer", "finished showing disclaimer");
}
public void promptRequiredUpdate(String Message) {
Log.d("required update","required!");
AlertDialog.Builder builder = new AlertDialog.Builder(
this);
builder.setMessage(Message)
.setCancelable(false)
.setPositiveButton("Update Now",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.d("SHOW ALERT -->!", "update");
triggerDownload();
dialog.cancel();
}
})
.setNegativeButton("Later",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.d("SHOW ALERT -->!", "cancel");
dialog.cancel();
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public boolean uploadDateEqualsDateInFile() {
Log.d("uploadDateEqualsDateInFile","comparing schedule upload dates");
getUploadDate();
try {
String recordedDate = "";
InputStream instream = openFileInput("update.txt");
if (instream != null) { // if file the available for reading
Log.d("uploadDateEqualsDateInFile","update.txt found!");
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line = null;
while ((line = buffreader.readLine()) != null) {
recordedDate = line;
Log.d("uploadDateEqualsDateInFile","recorded:"+recordedDate);
}
Log.d("uploadDateEqualsDateInFile","last upload date: " + str + ", recorded:" +recordedDate);
if(str.equals(recordedDate)) return true;
return false;
}
Log.d("uploadDateEqualsDateInFile","update.txt is null!");
return false;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public void showAlert(String Message) {
AlertDialog.Builder builder = new AlertDialog.Builder(getBaseContext());
builder.setMessage(Message).setCancelable(false)
.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public boolean checkInternet() {
ConnectivityManager cm = (ConnectivityManager) this
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo infos[] = cm.getAllNetworkInfo();
for (NetworkInfo info : infos)
if (info.getState() == NetworkInfo.State.CONNECTED
|| info.getState() == NetworkInfo.State.CONNECTING) {
return true;
}
return false;
}
public boolean dbExists() {
File database=getApplicationContext().getDatabasePath(DatabaseHandler.DATABASE_NAME);
if (!database.exists()) {
Log.i("Database", "Not Found");
return false;
}
Log.i("Database", "Found");
return true;
}
#Override
protected void onDestroy() {
super.onDestroy();
if (db != null) {
db.close();
}
}
#Override
protected void onPause() {
super.onPause();
if (db != null) {
db.close();
}
}
}
simplymoody, do what Chirag Raval suggested by declaring private static TextView homeText1, globally and in your onCreate initialise them. However, you should always update the UI from the main thread. But showDisclaimer() is still running on the background thread, so you could run the showDisclaimer() a couple of different ways. One would be to do what you have done in getUploadDate():
runOnUiThread(new Runnable() {
public void run() {
showDisclaimer()
}
});
Or you could use a handler:
private Handler showDisclaimerHandler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
homeText3x.setText("TEXT");
homeText1x.setVisibility(View.VISIBLE);
homeText2x.setVisibility(View.VISIBLE);
homeText3x.setVisibility(View.VISIBLE);
homeText4x.setVisibility(View.VISIBLE);
Log.d("ShowDisclaimer", "finished showing disclaimer");
return false;
}
});
And everywhere in a background thread you wish to run your showDisclaimer(), instead you run:
showDisclaimerHandler.sendEmptyMessage(0);

Categories

Resources