Customize text inside Edittext for chatting - java

I want to customize the text inside the edittext of my chatting app. I want to bold the username and normal font for his message.
For example;
usernamejay: Hi This is Jay. How are you?
also make 1 space for reply after the message of usernamejay. i also want to change font color of username. Also if possible put message balloon for every message.
Example:
usernamejay: Hi This is Jay. How are you?
usernameclark: I'm Fine. Can i call you now for a meeting?
Can anyone help me how. This is the code for Java
import java.io.UnsupportedEncodingException;
import com.example.healthhelpv2.*;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import at.vcity.androidim.interfaces.IAppManager;
import at.vcity.androidim.services.IMService;
import at.vcity.androidim.tools.FriendController;
import at.vcity.androidim.tools.LocalStorageHandler;
import at.vcity.androidim.types.FriendInfo;
import at.vcity.androidim.types.MessageInfo;
public class Messaging extends Activity {
private static final int MESSAGE_CANNOT_BE_SENT = 0;
public String username;
private EditText messageText;
private EditText messageHistoryText;
private Button sendMessageButton;
private IAppManager imService;
private FriendInfo friend = new FriendInfo();
private LocalStorageHandler localstoragehandler;
private Cursor dbCursor;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
imService = ((IMService.IMBinder)service).getService();
}
public void onServiceDisconnected(ComponentName className) {
imService = null;
Toast.makeText(Messaging.this, R.string.local_service_stopped,
Toast.LENGTH_SHORT).show();
}
};
#Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.messaging_screen); //messaging_screen);
messageHistoryText = (EditText) findViewById(R.id.messageHistory);
messageText = (EditText) findViewById(R.id.message);
messageText.requestFocus();
sendMessageButton = (Button) findViewById(R.id.sendMessageButton);
Bundle extras = this.getIntent().getExtras();
friend.userName = extras.getString(FriendInfo.USERNAME);
friend.ip = extras.getString(FriendInfo.IP);
friend.port = extras.getString(FriendInfo.PORT);
String msg = extras.getString(MessageInfo.MESSAGETEXT);
setTitle("Messaging with " + friend.userName);
// EditText friendUserName = (EditText) findViewById(R.id.friendUserName);
// friendUserName.setText(friend.userName);
localstoragehandler = new LocalStorageHandler(this);
dbCursor = localstoragehandler.get(friend.userName, IMService.USERNAME );
if (dbCursor.getCount() > 0){
int noOfScorer = 0;
dbCursor.moveToFirst();
while ((!dbCursor.isAfterLast())&&noOfScorer<dbCursor.getCount())
{
noOfScorer++;
this.appendToMessageHistory(dbCursor.getString(2) , dbCursor.getString(3));
dbCursor.moveToNext();
}
}
localstoragehandler.close();
if (msg != null)
{
this.appendToMessageHistory(friend.userName , msg);
((NotificationManager)getSystemService(NOTIFICATION_SERVICE)).cancel((friend.userName+msg).hashCode());
}
sendMessageButton.setOnClickListener(new OnClickListener(){
CharSequence message;
Handler handler = new Handler();
public void onClick(View arg0) {
message = messageText.getText();
if (message.length()>0)
{
appendToMessageHistory(imService.getUsername(), message.toString());
localstoragehandler.insert(imService.getUsername(), friend.userName, message.toString());
messageText.setText("");
Thread thread = new Thread(){
public void run() {
try {
if (imService.sendMessage(imService.getUsername(), friend.userName, message.toString()) == null)
{
handler.post(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(),R.string.message_cannot_be_sent, Toast.LENGTH_LONG).show();
//showDialog(MESSAGE_CANNOT_BE_SENT);
}
});
}
} catch (UnsupportedEncodingException e) {
Toast.makeText(getApplicationContext(),R.string.message_cannot_be_sent, Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
};
thread.start();
}
}});
messageText.setOnKeyListener(new OnKeyListener(){
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if (keyCode == 66){
sendMessageButton.performClick();
return true;
}
return false;
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
int message = -1;
switch (id)
{
case MESSAGE_CANNOT_BE_SENT:
message = R.string.message_cannot_be_sent;
break;
}
if (message == -1)
{
return null;
}
else
{
return new AlertDialog.Builder(Messaging.this)
.setMessage(message)
.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked OK so do some stuff */
}
})
.create();
}
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(messageReceiver);
unbindService(mConnection);
FriendController.setActiveFriend(null);
}
#Override
protected void onResume()
{
super.onResume();
bindService(new Intent(Messaging.this, IMService.class), mConnection , Context.BIND_AUTO_CREATE);
IntentFilter i = new IntentFilter();
i.addAction(IMService.TAKE_MESSAGE);
registerReceiver(messageReceiver, i);
FriendController.setActiveFriend(friend.userName);
}
public class MessageReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
Bundle extra = intent.getExtras();
String username = extra.getString(MessageInfo.USERID);
String message = extra.getString(MessageInfo.MESSAGETEXT);
if (username != null && message != null)
{
if (friend.userName.equals(username)) {
appendToMessageHistory(username, message);
localstoragehandler.insert(username,imService.getUsername(), message);
}
else {
if (message.length() > 15) {
message = message.substring(0, 15);
}
Toast.makeText(Messaging.this, username + " says '"+
message + "'",
Toast.LENGTH_SHORT).show();
}
}
}
};
private MessageReceiver messageReceiver = new MessageReceiver();
public void appendToMessageHistory(String username, String message) {
if (username != null && message != null) {
messageHistoryText.append(username + ":\n");
messageHistoryText.append(message + "\n");
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (localstoragehandler != null) {
localstoragehandler.close();
}
if (dbCursor != null) {
dbCursor.close();
}
}
}
The XML messaging_screen
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ccbfbf"
android:orientation="vertical"
android:padding="10dip" >
<!--
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dip"
android:text="Friend:"
/>
<EditText android:id="#+id/friendUserName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:singleLine="true"
android:editable="false" />
-->
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dip"
android:text="Messages:"/>
<EditText android:id="#+id/messageHistory"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true"
android:layout_weight="1"
android:editable="false"
android:gravity="top"
android:scrollbars="vertical"
android:scrollbarSize="10px"
/>
<LinearLayout android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="4">
<EditText
android:id="#+id/message"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="top"
android:hint="Type message here!" />
<Button android:id="#+id/sendMessageButton"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="4"
android:text="Send"/>
</LinearLayout>
</LinearLayout>

Do this way Hope this works for you
EditText editText = (EditText)findViewById(R.id.editText);
String userName = "usernamejay";
String message = "Hi This is Jay. How are you?";
String finalStr = "<b>"+userName+":</b> "+message+"";
editText.setText(Html.fromHtml(finalStr));

On Android you can use HTML to style the text inside a TextView, see here http://daniel-codes.blogspot.pt/2011/04/html-in-textviews.html

You could also use a spannable string, may be you could look at a portion of the code in this answer.
A code extract from the link
final SpannableString out0 = new SpannableString(source[position]);
StyleSpan boldSpan = new StyleSpan(Typeface.BOLD);
out0.setSpan(boldSpan, 6, 17, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
holder.tv.setText(out0);
P.S: but please read the solution in the link before you start applying things in your code.

Related

Setting start and end duration of song with range seekbar

I'm trying to incorporate somehow into Android audio player, functionality of marking of the fragment of the song in the player that it is supposed to play. I see this like clipping of the fragment as in Audacity. I'm trying to get it with a range seekbar (two blue dots on a line that can be adjust) on which user mark the beginning and the end to play and when replay mode is enabled the player will play that marked section over and over again.
It looks like on this image
The application is written in the Java language.
Below are the related code.
Dependency
implementation 'com.yahoo.mobile.client.android.util.rangeseekbar:rangeseekbar-
library:0.1.0'
PlayerActivity.java
package com.example.marcin.playerexperiment;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.media.AudioAttributes;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import com.yahoo.mobile.client.android.util.rangeseekbar.RangeSeekBar;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class PlayerActivity extends AppCompatActivity {
RangeSeekBar<Integer> mRangeSeekBar;
MediaPlayer mMediaPlayer;
Button playButton, openButton, replayButton;
int max;
SeekBar mSeekBar;
public static final int PICK_FILE =99;
ScheduledExecutorService timer;
TextView title, elapse, mEndTextView;
String duration;
Boolean isRepeat = false;
Runnable mRunnable;
Handler mHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
//otwórz
openButton = findViewById(R.id.open);
//powtórz
replayButton = findViewById(R.id.replayButton);
//range seekbar
mRangeSeekBar = findViewById(R.id.rangeSeekBar);
//seekbar - linia dzwięku
mSeekBar = findViewById(R.id.seekBar);
//mRangeSeekBar.setNotifyWhileDragging(true);
title = (TextView) findViewById(R.id.title);
elapse = (TextView) findViewById(R.id.elapse);
playButton = findViewById(R.id.play);
// mEndTextView = findViewById(R.id.end_duration);
mHandler = new Handler();
//Odtwórz |>
playButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mMediaPlayer != null){
if(mMediaPlayer.isPlaying()){
mMediaPlayer.pause();
playButton.setText("ODTWÓRZ");
timer.shutdown();
}else{
mMediaPlayer.start();
playButton.setText("PAUZA");
timer = Executors.newScheduledThreadPool(1);
timer.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
// playProgress ();
if (mMediaPlayer != null) {
if (!mSeekBar.isPressed()) {
mSeekBar.setProgress(mMediaPlayer.getCurrentPosition());
}
}
}
},10,10, TimeUnit.MILLISECONDS);
}
}
}
});
//otwieranie pliku dzwiękowego
openButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("audio/*");
startActivityForResult(intent, PICK_FILE);
}
});
mRangeSeekBar.setOnRangeSeekBarChangeListener(new RangeSeekBar.OnRangeSeekBarChangeListener<Integer>() {
#Override
public void onRangeSeekBarValuesChanged(RangeSeekBar<?> bar, Integer minValue, Integer maxValue) {
mMediaPlayer.seekTo(minValue);
max = maxValue;
String infoMax = String.valueOf(max);
Log.i("MAX", infoMax);
}
});
mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
if (mMediaPlayer != null){
int millis = mMediaPlayer.getCurrentPosition();
long total_secs = TimeUnit.SECONDS.convert(millis, TimeUnit.MILLISECONDS);
long mins = TimeUnit.MINUTES.convert(total_secs, TimeUnit.SECONDS);
long secs = total_secs - (mins*60);
elapse.setText(mins + ":" + secs + " / " + duration);
//Log.i("Duration:", duration);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
if (mMediaPlayer != null) {
mMediaPlayer.seekTo(seekBar.getProgress());
}
}
});
//Loop
replayButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//repeat = false
if(isRepeat){
isRepeat = false;
mMediaPlayer.setLooping(false);
replayButton.setText("Powtórka wyłączona");
Toast.makeText(PlayerActivity.this, "Tryb powtórki jest wyłączony", Toast.LENGTH_SHORT).show();
}else{
isRepeat = true;
mMediaPlayer.setLooping(true);
replayButton.setText("Powtórka włączona");
Toast.makeText(PlayerActivity.this, "Tryb powtórki jest włączony", Toast.LENGTH_SHORT).show();
}
//mediaPlayer.setLooping(true);
// Toast.makeText(PlayerActivity.this, "Repeat if ON", Toast.LENGTH_SHORT).show();
}
});
playButton.setEnabled(false);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_FILE && resultCode == RESULT_OK){
if (data != null){
Uri uri = data.getData();
createMediaPlayer(uri);
}
}
}
public void createMediaPlayer(Uri uri){
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setAudioAttributes(
new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.setUsage(AudioAttributes.USAGE_MEDIA)
.build()
);
try {
mMediaPlayer.setDataSource(getApplicationContext(), uri);
mMediaPlayer.prepare();
title.setText(getNameFromUri(uri));
playButton.setEnabled(true);
mRangeSeekBar.setNotifyWhileDragging(true);
mRangeSeekBar.setRangeValues(0, mMediaPlayer.getDuration());
max = mMediaPlayer.getDuration();
mSeekBar.setMax(max);
mSeekBar.setProgress(0);
long total_secs = TimeUnit.SECONDS.convert(max, TimeUnit.MILLISECONDS);
long mins = TimeUnit.MINUTES.convert(total_secs, TimeUnit.SECONDS);
long secs = total_secs - (mins*60);
duration = mins + ":" + secs;
elapse.setText("00:00 / " + duration);
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
releaseMediaPlayer();
}
});
} catch (IOException e){
title.setText(e.toString());
}
}
#SuppressLint("Range")
public String getNameFromUri(Uri uri){
String fileName = "";
Cursor cursor = null;
cursor = getContentResolver().query(uri, new String[]{
MediaStore.Images.ImageColumns.DISPLAY_NAME
}, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
fileName = cursor.getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DISPLAY_NAME));
}
if (cursor != null) {
cursor.close();
}
return fileName;
}
private void playProgress () {
if (mMediaPlayer.getCurrentPosition() == max) {
mMediaPlayer.stop();
}
if (mMediaPlayer.isPlaying()) {
mRunnable = new Runnable() {
#Override
public void run() {
playProgress();
}
};
mHandler.postDelayed(mRunnable, 0);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
releaseMediaPlayer();
}
public void releaseMediaPlayer(){
if (timer != null) {
timer.shutdown();
}
if (mMediaPlayer != null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
playButton.setEnabled(false);
elapse.setText("TYTUL");
elapse.setText("00:00 / 00:00");
mSeekBar.setMax(100);
mSeekBar.setProgress(0);
}
}
Activity_player.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".PlayerActivity">
<Button
android:id="#+id/play"
android:layout_width="wrap_content"
android:layout_height="37dp"
android:layout_marginStart="150dp"
android:layout_marginEnd="173dp"
android:text="Play"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/seekBar" />
<com.yahoo.mobile.client.android.util.rangeseekbar.RangeSeekBar
android:id="#+id/rangeSeekBar"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="357dp"
android:layout_marginBottom="20dp"
app:layout_constraintBottom_toTopOf="#+id/seekBar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/elapse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="287dp"
android:layout_marginBottom="51dp"
android:text="00-00"
app:layout_constraintBottom_toTopOf="#+id/rangeSeekBar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.461"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0" />
<SeekBar
android:id="#+id/seekBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/rangeSeekBar" />
<androidx.constraintlayout.widget.Barrier
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:barrierDirection="top"
tools:layout_editor_absoluteX="92dp"
tools:layout_editor_absoluteY="357dp" />
<Button
android:id="#+id/open"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="154dp"
android:layout_marginEnd="163dp"
android:layout_marginBottom="140dp"
android:backgroundTint="#color/teal_200"
android:text="Open file"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/play" />
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="173dp"
android:layout_marginEnd="202dp"
app:layout_constraintBottom_toTopOf="#+id/elapse"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.824" />
<Button
android:id="#+id/replayButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="150dp"
android:layout_marginEnd="142dp"
android:backgroundTint="#color/purple_500"
android:text="Replay"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/open" />
</androidx.constraintlayout.widget.ConstraintLayout>

Variable string in setCommand function of JSch Android

I want to execute the following command through ssh on my raspberry pi from Android App:
echo 'value of a variable string named cmd' > filename.txt
I tried following:
String a="echo '";
String c="' > filename.txt";
String cmd=a+clip+b;
channelSsh.setCommand(cmd);
Normal commands like "sudo reboot" works but not this!
My Program is a bit long but You can find a simple program of JSch implementation Here (The second answer).
If you still want to look at my code (things are in copyMethod() and executeRemoteCommand() function):
JAVA:
package com.quickclip.panky.quickclip;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import java.io.ByteArrayOutputStream;
import java.util.Properties;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
EditText e1;
Button b1,b2,b3;
TextView t1,t2;
Activity activity = this;
static int flag=2,time=3000;
static ClipData clip=null;
String output;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e1 = (EditText) findViewById(R.id.editText);
t1 = (TextView) findViewById(R.id.textView);
t2 = (TextView) findViewById(R.id.textView3);
b1 = (Button) findViewById(R.id.button1);
b2 = (Button) findViewById(R.id.button2);
b3 = (Button) findViewById(R.id.button3);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CopyMethod();
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
VolDown();
}
});
b3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CopyPace();
}
});
Runnable myRunnable = new Runnable() {
#Override
public void run() {
while (true) {
if (flag % 2 == 0) {
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else if (flag % 2 != 0) {
try {
Thread.sleep(800);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
activity.runOnUiThread(new Runnable() {
public void run() {
CopyMethod();
flag += 1;
}
});
}
}
};
Thread myThread = new Thread(myRunnable);
myThread.start();
}
public void VolDown(View view) {VolDown();}
public void CopyPace(View view) {CopyPace();}
public void ManCopy(View view) {CopyMethod();}
public void VolDown() {
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("Copied Text","decrease volume");
clipboard.setPrimaryClip(clip);
}
public void CopyPace() {
if(time==5000) time=2000;
else if(time<5000) time+=1000;
t1.setText("Automatically Sending in: "+(time/1000)+" sec");
}
public void CopyMethod() {
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("Copied Text", (CharSequence) e1.getText().toString());
clipboard.setPrimaryClip(clip);
new AsyncTask<Integer, Void, Void>(){
#Override
protected Void doInBackground(Integer... params) {
try {
output=executeRemoteCommand();
t2.setText(output);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}.execute(1);
e1.setText("");
}
public static String executeRemoteCommand()
throws Exception {
String username="pi";
String password="10<,mmXLSQ";
String hostname="192.168.43.41";
int port=22;
String a="echo '",c="' > yo.txt";
JSch jsch = new JSch();
Session session = jsch.getSession(username, hostname, port);
session.setPassword(password);
// Avoid asking for key confirmation
Properties prop = new Properties();
prop.put("StrictHostKeyChecking", "no");
session.setConfig(prop);
session.connect();
// SSH Channel
ChannelExec channelSsh = (ChannelExec)
session.openChannel("exec");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
channelSsh.setOutputStream(baos);
// Execute command
String cmd=a+clip+c;
channelSsh.setCommand(cmd);
channelSsh.connect();
channelSsh.disconnect();
return baos.toString();
}
#Override
public void onClick(View view) {CopyMethod();VolDown();CopyPace();}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<android.widget.RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.quickclip.panky.quickclip.MainActivity">
<EditText
android:id="#+id/editText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:ems="100"
android:inputType="textAutoCorrect" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_below="#+id/editText"
android:text="Send it Now"
android:onClick="ManCopy"/>
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/editText"
android:text="Volume Down"
android:onClick="VolDown"/>
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText"
android:layout_centerHorizontal="true"
android:text="Switch Pace"
android:onClick="CopyPace"/>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/button"
android:layout_centerHorizontal="true"
android:textSize="20dp"
android:layout_marginTop="130dp"
android:text="Automatically Sending in: 3 sec" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true"
android:textSize="20dp"
android:text="Speak/Type in this time" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView2"
android:layout_centerHorizontal="true"
android:textSize="20dp"
android:text="Connecting to SSH" />
</android.widget.RelativeLayout>
the clip inside the executeRemoteCommand() method in always null where you used String cmd=a+clip+c;
And you are calling ClipData.toString() here which returns string representation of the object
to get the text from ClipData use
String text = "";
ClipData clip = getPrimaryClip();
if (clip != null && clip.getItemCount() > 0) {
text = clip.getItemAt(0).coerceToText(mContext);
}
it will retrieves the primary clip and coerce it to a string
use Log to log the command before executing and check if you are using the correct command
I solved my problem,... thankyou for your time... thnx Arpan...
package com.quickclip.panky.quickclip;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import java.io.ByteArrayOutputStream;
import java.util.Properties;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
EditText e1;
Button b1,b2,b3;
TextView t1,t2;
Activity activity = this;
static int flag=2,time=3000;
static ClipData clip=null;
String output;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e1 = (EditText) findViewById(R.id.editText);
t1 = (TextView) findViewById(R.id.textView);
t2 = (TextView) findViewById(R.id.textView3);
b1 = (Button) findViewById(R.id.button1);
b2 = (Button) findViewById(R.id.button2);
b3 = (Button) findViewById(R.id.button3);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CopyMethod();
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
VolDown();
}
});
b3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CopyPace();
}
});
Runnable myRunnable = new Runnable() {
#Override
public void run() {
while (true) {
if (flag % 2 == 0) {
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else if (flag % 2 != 0) {
try {
Thread.sleep(800);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
activity.runOnUiThread(new Runnable() {
public void run() {
CopyMethod();
flag += 1;
}
});
}
}
};
Thread myThread = new Thread(myRunnable);
myThread.start();
}
public void VolDown(View view) {VolDown();}
public void CopyPace(View view) {CopyPace();}
public void ManCopy(View view) {CopyMethod();}
public void VolDown() {
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("Copied Text","decrease volume");
clipboard.setPrimaryClip(clip);
}
public void CopyPace() {
if(time==5000) time=2000;
else if(time<5000) time+=1000;
t1.setText("Automatically Sending in: "+(time/1000)+" sec");
}
public void CopyMethod() {
final String username="pi";
final String password="10<,mmXLSQ";
final String hostname="192.168.43.41";
final int port=22;
final String a="echo '",c="' > panky.txt";
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
final ClipData clip = ClipData.newPlainText("Copied Text", (CharSequence) e1.getText().toString());
clipboard.setPrimaryClip(clip);
new AsyncTask<Integer, Void, Void>(){
#Override
protected Void doInBackground(Integer... params) {
try {
JSch jsch = new JSch();
Session session = jsch.getSession(username, hostname, port);
session.setPassword(password);
// Avoid asking for key confirmation
Properties prop = new Properties();
prop.put("StrictHostKeyChecking", "no");
session.setConfig(prop);
session.connect();
// SSH Channel
ChannelExec channelSsh = (ChannelExec)
session.openChannel("exec");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
channelSsh.setOutputStream(baos);
// Execute command
String cmd=a+clip+c;
channelSsh.setCommand(cmd);
channelSsh.connect();
channelSsh.disconnect();
t2.setText(output);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}.execute(1);
e1.setText("");
}
#Override
public void onClick(View view) {CopyMethod();VolDown();CopyPace();}
}

How to put a progress bar with thread safety in android while hitting a server and waiting for response?

I have an application where I am recording audio in an activity. User has a start recording and stop recording button to do that. Once user clicks the stop recording button, it sends the recorded mp3 file to server (encoded string) and server process it and a response is received. I want to do the following tasks:
Since this process is long, I want to do this in a separate thread(preferably).
The process of sending and receiving response is to be shown using progress bar.
User should be able to navigate to other screens while he is waiting(i.e. current activity may be destroyed)
I tried using Toast messages before and after the function where I send mp3 to server. But there is no sync, sometimes msg comes early, sometime it's late. That's why a proper progress bar is required.How to do this? Can AsyncTask be used with what I want to achieve in (3). or should I use some other form of multithreading. Please help.Below is the activity
(Please ignore the indentations, I couldn't fix the code on stack-overflow:
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class RecordActivity extends AppCompatActivity {
private static final String LOG_TAG = "AudioRecordTest";
private static String msg = "default";
public final static String Result_MESSAGE = "in.innovatehub.ankita_mehta.tinyears.ResultMESSAGE";
private static final int REQUESTCODE_RECORDING = 109201;
private Button mRecorderApp = null;
private static String mFileName = "music.mp3";
private static String mFilePath = String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS + "/TinyEars/"));
private MediaRecorder mRecorder = null;
private MediaPlayer mPlayer = null;
private ImageButton mRecordImageButton = null;
private ImageButton mPlayImageButton = null;
boolean mStartRecording = true;
boolean mStartPlaying = true;
private Button mShowStatsButton = null;
private static final String TAG = "RecordActivity";
private Handler handler = new Handler();
final Runnable updater = new Runnable() {
public void run() {
handler.postDelayed(this, 1);
if(mRecorder!=null) {
int maxAmplitude = mRecorder.getMaxAmplitude();
if (maxAmplitude != 0) {
// visualizerView.addAmplitude(maxAmplitude);
}
}
else{
}
}
};
private void onRecord(boolean start) {
if (start) {
startRecording();
} else {
stopRecording();
}
}
private void onPlay(boolean start) {
if (start) {
startPlaying();
} else {
stopPlaying();
}
}
private void startPlaying() {
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(mFilePath+"/"+mFileName);
mPlayer.prepare();
mPlayer.start();
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
Log.i("Completion Listener", "Song Complete");
stopPlaying();
mRecordImageButton.setEnabled(true);
}
});
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
}
private void stopPlaying() {
if (mPlayer != null) {
mPlayer.reset();
mPlayer.release();
mPlayer = null;
mPlayImageButton.setImageResource(R.drawable.playicon);
// mStartPlaying = true;
} else {
mPlayImageButton.setImageResource(R.drawable.pauseicon);
// mStartPlaying = false;
}
}
private void startRecording() {
AudioRecordTest(String.valueOf(System.currentTimeMillis()));
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mRecorder.setOutputFile(mFilePath+"/"+mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
try {
mRecorder.start();
Toast.makeText(getApplicationContext(), "Recording started", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Log.e(LOG_TAG, "start() failed");
}
}
private void stopRecording() {
if (mRecorder != null) {
mRecorder.stop();
mRecorder.release();
Toast.makeText(getApplicationContext(), "Audio recorded successfully",Toast.LENGTH_LONG).show();
mRecorder = null;
mRecordImageButton.setImageResource(R.drawable.micicon);
// mStartRecording = true;
} else {
mRecordImageButton.setImageResource(R.drawable.stopicon);
// mStartRecording = false;
}
}
public void AudioRecordTest(String text) {
boolean exists = (new File(mFilePath+"/"+mFileName)).exists();
if (!exists) {
new File(mFileName).mkdirs();
}
// mFileName += "audiorecordtest.mp3";
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_record);
Log.d(TAG,"HERE IS FILE PATH"+mFilePath+"/"+mFileName);
mRecordImageButton = (ImageButton) findViewById(R.id.imageButton2);
mPlayImageButton = (ImageButton) findViewById(R.id.imageButton3);
mShowStatsButton = (Button) findViewById(R.id.showMeStats);
mRecorderApp = (Button) findViewById(R.id.recorderApp);
AudioRecordTest("00000");
mRecordImageButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
onRecord(mStartRecording);
if (mStartRecording) {
mRecordImageButton.setImageResource(R.drawable.stopicon);
mPlayImageButton.setEnabled(false);
//setText("Stop recording");
} else {
mRecordImageButton.setImageResource(R.drawable.micicon);
mPlayImageButton.setEnabled(true);
mShowStatsButton.setEnabled(true);
mShowStatsButton.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(),"Hold on... we are getting the results!",Toast.LENGTH_SHORT).show();
pressedSavBtn();
Toast.makeText(getApplicationContext(),"Parsing done ... now you may see the results!",Toast.LENGTH_SHORT).show();
//setText("Start recording");
}
mStartRecording = !mStartRecording;
}
});
mPlayImageButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
onPlay(mStartPlaying);
if (mStartPlaying) {
mPlayImageButton.setImageResource(R.drawable.pauseicon);
mRecordImageButton.setEnabled(false);
mShowStatsButton.setEnabled(false);
//setText("Stop playing");
} else {
mPlayImageButton.setImageResource(R.drawable.playicon);
mRecordImageButton.setEnabled(true);
mShowStatsButton.setEnabled(false);
//setText("Start playing");
}
mStartPlaying = !mStartPlaying;
}
});
//Calling recorder ...
mRecorderApp.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
Intent intent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
if (isAvailable(getApplicationContext(), intent)) {
startActivityForResult(intent, REQUESTCODE_RECORDING);
}
}
});
mShowStatsButton = (Button) findViewById(R.id.showMeStats);
mShowStatsButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
sendResults(msg);
}
});
}
public void pressedSavBtn(){
try {
thread.start();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
mShowStatsButton.setVisibility(View.VISIBLE);
}
}
public void writeToFile(String data)
{
// Get the directory for the user's public pictures directory.
final File path = new File(mFilePath+"/");
// Make sure the path directory exists.
if(!path.exists())
{
// Make it, if it doesn't exit
path.mkdirs();
}
final File file = new File(path, "config.txt");
// Save your stream, don't forget to flush() it before closing it.
try
{
file.createNewFile();
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(data);
myOutWriter.close();
fOut.flush();
fOut.close();
}
catch (IOException e)
{
Log.e("Exception", "File write failed: " + e.toString());
}
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append((line + "\n"));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
//THIS IS FILE ENCODING CODE
File file = new File(mFilePath+"/"+mFileName);
byte[] bytes = FileUtils.readFileToByteArray(file);
String encoded = Base64.encodeToString(bytes, 0);
Log.d("~~~~~~~~ Encoded: ", encoded);
writeToFile(encoded);
//THIS IS URL CONN CODE
String link = "http://192.168.50.0:9000/divide_result";
URL url = new URL(link);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(link);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("Name", "StackOverFlow"));
nameValuePairs.add(new BasicNameValuePair("Date", encoded));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
String sb = convertStreamToString(response.getEntity().getContent());
Log.d(TAG,"MESSAGE NOW"+sb);
Log.d(TAG, sb);
msg = sb.toString();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
public void sendResults(String res){
Log.d(TAG, "Inside on create, Navigating to Result Screen Activity!");
Intent intent = new Intent(getApplicationContext(), ResultsScreenActivity.class);
intent.putExtra(Result_MESSAGE, res);
startActivity(intent);
}
public static boolean isAvailable(Context ctx, Intent intent) {
final PackageManager mgr = ctx.getPackageManager();
List<ResolveInfo> list = mgr.queryIntentActivities(intent,PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == REQUESTCODE_RECORDING) {
if (resultCode == RESULT_OK) {
Uri audioUri = intent.getData();
// make use of this MediaStore uri
// e.g. store it somewhere
}
else {
// react meaningful to problems
}
}
else {
super.onActivityResult(requestCode,
resultCode, intent);
}
}
#Override
public void onPause() {
super.onPause();
if (mRecorder != null) {
mRecorder.release();
mRecorder = null;
}
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
thread.stop();
}
#Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacks(updater);
if(mRecorder!=null) {
mRecorder.stop();
mRecorder.reset();
mRecorder.release();
}
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
handler.post(updater);
}
}
Also below is the layout-xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_record"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center|center_horizontal"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:screenOrientation="portrait"
android:orientation="vertical"
tools:context="in.innovatehub.mobile.ankita_mehta.tinyears.RecordActivity">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/linearLayout_record"
android:orientation="vertical"
android:gravity="center">
<ImageButton
android:id="#+id/imageButton2"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:scaleType="fitXY"
android:src="#drawable/micicon" />
<ImageButton
android:id="#+id/imageButton3"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:scaleType="fitXY"
android:src="#drawable/playicon" />
<Button
android:id="#+id/showMeStats"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:visibility="gone"
android:onClick="loadStats"
android:text="#string/showMeStats" />
<Button
android:id="#+id/recorderApp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible"
android:gravity="center"
android:text="#string/UseRecorderApp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/loadStatsLinearLayout"
android:gravity="center"
android:visibility="gone"
android:orientation="vertical">
<TextView
android:id="#+id/loadingMessage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/loadingMessage"
/>
<ProgressBar
android:id="#+id/downloadProgress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:indeterminate="true"
/>
</LinearLayout>
</LinearLayout>
You can use an IntentService to upload your content to the server. By default, it runs on a seperate thread and is not activity bound. Then use a broadcast receiver to communicate the result back to any activity. You can find an example here.
For the progress bar, you can create a notification and show the progress bar there, this will not block your application's UI.
For hitting the server at you should use AsyncTask or Runnable thread, without disturb the main tread
for custome progress dialog use the following code
xml file.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:background="#color/color_white"
android:padding="5dp" >
<ProgressBar
android:id="#+id/layCustomContentProgress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/layCustomProgressHeading"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/layCustomProgressInfo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
</LinearLayout>
</LinearLayout>
and the method
public Dialog getCustomPogressDialog(Context context, String heading, String text) {
// Declare the customer dialog
Dialog dlgProgress = new Dialog(context);
// Set no title for the dialog
dlgProgress.requestWindowFeature(Window.FEATURE_NO_TITLE);
// Set the content view to the customer_alert layout
dlgProgress.setContentView(R.layout.layout_custom_process_progress);
// Cancel the dialog when touched outside.
dlgProgress.setCanceledOnTouchOutside(false);
// Set the main heading
TextView dlgHeading = (TextView) dlgProgress.findViewById(R.id.layCustomProgressHeading);
dlgHeading.setText(heading);
// set the info
TextView dlgInfo = (TextView) dlgProgress.findViewById(R.id.layCustomProgressInfo);
dlgInfo.setText(text);
// Return the refenrece to the dialog
return dlgProgress;
}

Onclicklistener only working once

My onclicklistener for my "LoginBtn". However that code inside that block only runs once and then doesn't run ever again. Please help me, I've tried everything. I know so because I have ran the log and it only logs out the value once and then never again.
package com.example.jj.test;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.ScaleDrawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatDrawableManager;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.goebl.david.Webb;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private static final String TAG = "test";
boolean loginform;
Button Loginbtn;
ImageView logoIV;
String email;
String password;
String token;
EditText emailET;
EditText passwordET;
final Webb webb = Webb.create();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Loginbtn = (Button) findViewById(R.id.loginbtn);
Loginbtn.setOnClickListener(this);
logoIV = (ImageView) findViewById(R.id.logoIV);
emailET = (EditText) findViewById(R.id.emailET);
passwordET = (EditText) findViewById(R.id.passwordET);
loginform = false;
ModifyEditText();
}
public void ModifyEditText(){
Drawable drawable = getResources().getDrawable(R.mipmap.email);
drawable.setBounds(0, 0, (int) (drawable.getIntrinsicWidth() * 0.6),
(int) (drawable.getIntrinsicHeight() * 0.6));
ScaleDrawable sd = new ScaleDrawable(drawable, 0, 40, 40);
emailET.setCompoundDrawables(null, null,sd.getDrawable(), null);
drawable = getResources().getDrawable(R.mipmap.password);
drawable.setBounds(0, 0, (int) (drawable.getIntrinsicWidth() * 0.6),
(int) (drawable.getIntrinsicHeight() * 0.6));
sd = new ScaleDrawable(drawable, 0, 40, 40);
passwordET.setCompoundDrawables(null, null, sd.getDrawable(), null);
final Drawable d = emailET.getBackground();
final Drawable nd = d.getConstantState().newDrawable();
nd.setColorFilter(AppCompatDrawableManager.getPorterDuffColorFilter(
Color.parseColor("#FFFFFF"), PorterDuff.Mode.SRC_IN));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
emailET.setBackground(nd);
passwordET.setBackground(nd);
}
}
public void startAnimation() {
Loginbtn.setText("Login");
logoIV.startAnimation(AnimationUtils.loadAnimation(this, R.anim.animmovetop));
Loginbtn.startAnimation(AnimationUtils.loadAnimation(this, R.anim.animmovedown));
Animation animFadeIn = AnimationUtils.loadAnimation(this, android.R.anim.fade_in);
emailET.setAnimation(animFadeIn);
passwordET.setAnimation(animFadeIn);
emailET.setVisibility(View.VISIBLE);
passwordET.setVisibility(View.VISIBLE);
Loginbtn.setBackgroundResource(R.drawable.transparentrectangel);
loginform = true;
}
public void LoginRequest(final JSONObject id) throws Exception {
final String testurl = "http://api.dermatrax.com/api/v1/token/generate?email="+email+"&password="+password+;
new AsyncTask<Void, Void, JSONObject>() {
#Override
protected JSONObject doInBackground(Void... params) {
try {
Log.d("TEST","Sending request");
JSONObject response = webb
.post(testurl)
.body(id)
.ensureSuccess()
.readTimeout(4000)
.asJsonObject()
.getBody();
return response;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject result) {
if (result != null) {
Log.d("TEST", result.toString());
try {
JSONObject data = result.getJSONObject("data");
token = data.get("token").toString();
Log.d("TEST", token);
if (token != null && !token.isEmpty()) {
Intent intent = new Intent(getApplicationContext(), UserData.class);
intent.putExtra("token", token);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
else{
Toast.makeText(getApplicationContext(),"Wrong email or password",Toast.LENGTH_LONG);
}
}
}.execute().get();
//executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.loginbtn){
Log.d("TEST", "loginform is = " + loginform);
JSONObject params = new JSONObject();
if (loginform == false) {
try {
startAnimation();
//LoginRequest(params);
} catch (Exception e) {
e.printStackTrace();
}
} else if (loginform == true) {
email = emailET.getText().toString();
password = passwordET.getText().toString();
try {
//params.put("email", email);
//params.put("password", password);
params.put("email", "blabla#combustiongroup.com");
params.put("password", "blabla");
LoginRequest(params);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
xml code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
tools:context="com.example.jj.test.MainActivity">
<RelativeLayout
android:background="#292446"
android:orientation="vertical"
android:id="#+id/midLL"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:padding="10dp"
android:layout_width="300dp"
android:gravity="center"
android:layout_height="40dp"
android:text="Go"
android:id="#+id/loginbtn"
android:textColor="#FFFFFF"
android:background="#drawable/roundbutton"
android:layout_below="#+id/logoIV"
android:layout_centerHorizontal="true" />
<de.hdodenhof.circleimageview.CircleImageView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/logoIV"
android:src="#mipmap/bigmatchlogo"
android:layout_width="70dp"
android:layout_height="70dp"
app:civ_border_width="2dp"
app:civ_border_color="#d6d6d6"
android:layout_alignBottom="#+id/emailET"
android:layout_centerHorizontal="true"
android:layout_marginBottom="20dp" />
<EditText
android:layout_marginBottom="10dp"
android:textColorHint="#FFFFFF"
android:hint="Email"
android:visibility="invisible"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:id="#+id/emailET"
android:layout_marginTop="217dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<EditText
android:drawableRight="#mipmap/password"
android:hint="Password"
android:textColorHint="#FFFFFF"
android:visibility="invisible"
android:layout_width="300dp"
android:layout_height="50dp"
android:inputType="textPassword"
android:ems="10"
android:layout_marginTop="10dp"
android:id="#+id/passwordET"
android:layout_below="#+id/emailET"
android:layout_alignLeft="#+id/emailET"
android:layout_alignStart="#+id/emailET" />
</RelativeLayout>
</LinearLayout>
Log cat
06-15 15:49:11.898 8631-8631/com.example.jj.test D/TEST: loginform is = false
06-15 15:50:36.598 8631-8631/com.example.jj.test D/szxszxszxszxszx: spannableStringBuilder.......1
06-15 15:50:36.598 8631-8631/com.example.jj.test D/szxszxszx: setSpan start is 0,end is 0,flags is 18boolena is false
Write this code inside onCreate()...
Loginbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(v.getId() == R.id.loginbtn){
Log.d("TEST", "loginform is = " + loginform);
JSONObject params = new JSONObject();
if (loginform == false) {
try {
startAnimation();
//LoginRequest(params);
} catch (Exception e) {
e.printStackTrace();
}
} else if (loginform == true) {
email = emailET.getText().toString();
password = passwordET.getText().toString();
try {
//params.put("email", email);
//params.put("password", password);
params.put("email", "blabla#combustiongroup.com");
params.put("password", "blabla");
LoginRequest(params);
} catch (Exception e) {
e.printStackTrace();
}
}
}

Android app activity button timeout selection

I have a basic android app using the zxing scanner and an activity with 3 buttons. The scanner sends a code to the activity, and the user can choose to clock in, clock out, or cancel the operation. This works fine. I want to add an auto timeout to this process, so that if the user does not click a button in a specific time period, the system will determine if they are in or out (cancel button must be pressed). I have the logic for all of this, but I don't know how to add the timeout logic. There is the initial layout, the activity Java code, the SQLite database object and handler, the zxing integration, and an ASync post. I have included the main java class below, which includes the onClick event and primary integration between zxing and the SQLite (those are omitted).
Any thoughts on how I could implement a basic timeout? I would like a function to be called from the main java class if a button is not pressed, and this function will determine (based on the last selection) if they are in or out.
Thanks for any help or suggestions you can provide.
Main Java Class
package com.neonet.neonetjobcardscanner;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.channels.FileChannel;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import com.neonet.neonetjobcardscanner.R;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
#SuppressWarnings("unused")
// remove before launch
public class ClockInOut extends Activity implements OnClickListener, OnInitListener {
private Button btnClockIn;
private Button btnClockOut;
private Button btnCancel;
private String employee;
private String operation;
private TextToSpeech tts;
private IntentIntegrator scanIntegrator;
private neonetpost post;
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, new Locale("en", "EN"));
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_clock_in_out);
btnClockIn = (Button) findViewById(R.id.btnClockIn);
btnClockOut = (Button) findViewById(R.id.btnClockOut);
btnCancel = (Button) findViewById(R.id.btnCancel);
btnClockIn.setOnClickListener(this);
btnClockOut.setOnClickListener(this);
btnCancel.setOnClickListener(this);
tts = new TextToSpeech(this, this);
tts.setLanguage(Locale.US);
scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan(); // optional scan type can be passed here
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.clock_in_out, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
post = new neonetpost();
String result = null;
String in = null;
String confirmation = null;
String now = df.format(new Date());
try {
SQLiteHandler db = new SQLiteHandler(getApplicationContext());
if (v.getId() == R.id.btnClockIn) {
in = "true";
if (operation != null)
confirmation = getString(R.string.ttsJobIn);
else
confirmation = getString(R.string.ttsClockIn);
Log.d("Insert: ", "Inserting...");
db.addTimeclockEntry(new TimeclockEntry(Integer.valueOf(employee), now, "IN"));
} else if (v.getId() == R.id.btnClockOut) {
in = "false";
if (operation != null)
confirmation = getString(R.string.ttsJobOut);
else
confirmation = getString(R.string.ttsClockOut);
db.addTimeclockEntry(new TimeclockEntry(Integer.valueOf(employee), now, "OUT"));
} else if (v.getId() == R.id.btnCancel) {
}
db.close();
db.exportDB(getApplicationContext());
if (in != null) {
post.execute(employee, operation, in);
while (result == null) {
result = post.result();
}
tts.speak(confirmation + " " + (operation!=null?result:""), TextToSpeech.QUEUE_FLUSH, null);
}
employee = operation = null;
} catch (Exception e) {
if (e != null) {
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
Log.e("JobCardScanner",
"ClockInOut.java onclick(): " + String.format(e.toString() + "%n" + errors.toString()));
}
}
if (post.hasError())
Log.e("JobCardScanner", "ClockInOut.java onclick(): " + (result == null ? "NULL" : result));
else
Log.i("JobCardScanner", "ClockInOut.java onClick(): " + (result == null ? "NULL" : result));
scanIntegrator.initiateScan(); // optional scan type can be passed here
}
#TargetApi(Build.VERSION_CODES.KITKAT)
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
try {
// retrieve scan result
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
// we have a result
final String scanContent = scanningResult.getContents();
// String scanFormat = scanningResult.getFormatName();
if (scanContent.indexOf("E") > -1) {
employee = scanContent.substring(2);
if (operation == null) {
btnClockIn.setText(R.string.btnClockIn);
btnClockOut.setText(R.string.btnClockOut);
} else {
btnClockIn.setText(R.string.btnOperationStart);
btnClockOut.setText(R.string.btnOperationEnd);
}
} else if (scanContent.indexOf("OP:") > -1) {
operation = scanContent.substring(3) + getString(R.string.operation_separator);
tts.speak(getString(R.string.ttsJobScan), TextToSpeech.QUEUE_FLUSH, null);
scanIntegrator.initiateScan();
}
Log.i("JobCardScanner",
"ClockInOut.java onActivityResult(): Received " + scanContent);
} else {
Log.i("JobCardScanner", "ClockInOut.java onActivityResult(): No scan data received");
}
} catch (Exception e) {
if (e != null) {
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
Log.e("JobCardScanner", "ClockInOut.java onActivityResult(): " + String.format(e.toString() + "%n" + errors.toString()));
}
}
}
#Override
public void onInit(int arg0) {
scanIntegrator.initiateScan();
}
}
Main Activity Layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.neonet.neonetjobcardscanner.ClockInOut" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/txtClockInOut"
android:textAlignment="center" />
<Button
android:id="#+id/btnClockIn"
style="#style/AppBaseTheme"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="25dp"
android:minHeight="#dimen/button_min_height"
android:minWidth="#dimen/button_min_width"
android:text="#string/btnClockIn"
android:textAlignment="center"
android:textSize="#dimen/button_text_size"
android:textStyle="bold" />
<Button
android:id="#+id/btnClockOut"
style="#style/AppBaseTheme"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/btnClockIn"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:minHeight="#dimen/button_min_height"
android:minWidth="#dimen/button_min_width"
android:text="#string/btnClockOut"
android:textAlignment="center"
android:textSize="#dimen/button_text_size"
android:textStyle="bold" />
<Button
android:id="#+id/btnCancel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/btnClockOut"
android:layout_centerHorizontal="true"
android:minHeight="#dimen/button_min_height"
android:minWidth="#dimen/button_min_width"
android:textAlignment="center"
android:textSize="#dimen/button_text_size"
android:textStyle="bold"
android:layout_marginTop="20dp"
android:text="#string/btnCancel" />
</RelativeLayout>
Main Activity Layout [Graphical]
http://i.stack.imgur.com/MSL5c.png
The Timer() class and subsequent examples did exactly what was needed!
Reference:
http://android-er.blogspot.com/2013/12/example-of-using-timer-and-timertask-on.html
http://developer.android.com/reference/java/util/Timer.html

Categories

Resources