[Q] [Q} Coding a system seting toggle - Android Q&A, Help & Troubleshooting

I am trying to make an app that on launch reads the current on/off(1,0) value of /sys/class/mdnie/mdnie/negative, then changes it to "0 or 1. Someone suggested the below, and I tried it and it does nothing any help is apreciated. Obvously I am a beginner and barely know how to write code but hey gotta start somewhere, this is for a visually impaired friend to toggle negative color mode by assigning a shortcut key to the app. I think it has to do with needing root permision to edit those settings.
Code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import android.app.Activity;
import android.os.Bundle;
public class ToggleNegativeColorsActivity extends Activity {
private static final String FILEPATH = "/sys/class/mdnie/mdnie/negative";
@Override
public void onCreate(Bundle savedInstanceState) {
try {
String value = readFileAsString(FILEPATH);
if ("1".equals(value.trim())) {
writeStringToFile(FILEPATH, "0");
}
else {
writeStringToFile(FILEPATH, "1");
}}
catch (IOException e) {
e.printStackTrace();
}
finish();
}
// Grabbed from http://stackoverflow.com/questions/1656797/how-to-read-a-file-into-string-in-java
private String readFileAsString(String filePath) throws IOException {
StringBuffer fileData = new StringBuffer();
BufferedReader reader = new BufferedReader(
new FileReader(filePath));
char[] buf = new char[1024];
int numRead;
while((numRead=reader.read(buf)) != -1){
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
}
reader.close();
return fileData.toString();
}
// Grabbed from http://stackoverflow.com/questions/1053467/how-do-i-save-a-string-to-a-text-file-using-java
private void writeStringToFile(String filePath, String value) throws IOException {
PrintWriter out = new PrintWriter(filePath);
out.print(value);
out.close();
}
}

Related

[Q] How to monitor socket status on simple tcp client

I have currently created a simple tcp socket client application that sends and receives messages from a dotnet server application I have created. The application itself actually works however there are a few things I would like to know if they are possible or not. Also this is my first ever droid application and my first ever java application so I am sure there is a better way to do what I have written so please go easy on me.
The problem that I am having is I need a way to monitor the status of the socket so that if the connection gets dropped whether it is from the server application ending or a network drop that the android client would disconnect and put a notification on the screen letting me know. Currently if I end the server application nothign happens on the client and it acts like the connection is still open. Granted this is probably due to the way I have it written so I am looking for samples or suggestions on how to change this so I can monitor this. Any help would be great. Eventually this will be put into a much larger project for my home but I am starting off small so I can do it correctly the first time rather than having someing messy later on.
My code is listed below.
Thanks
KJ
Source:
package com.kkearney.tcp1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class TCPClient1Activity extends Activity {
public static final int BUFFER_SIZE = 2048;
private Socket sck = null;
private PrintWriter out = null;
private BufferedReader in = null;
Button btnSend;
Button btnConnect;
Button btnDisconnect;
EditText textOut;
TextView textIn;
String response = "";
final Handler handler = new Handler();
final Runnable updateUI = new Runnable() {
public void run() {
textIn.setText(response);
}
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textOut = (EditText)findViewById(R.id.txtSend);
textIn = (TextView)findViewById(R.id.txtMSG);
btnSend = (Button)findViewById(R.id.btnSend);
btnConnect = (Button)findViewById(R.id.btnConnect);
btnDisconnect = (Button)findViewById(R.id.btnDisconnect);
}
public void ConnectUp(View view){
OpenConnection();
}
public void OpenConnection(){
new Thread(new Runnable(){
public void run(){
try{
if (sck == null){
sck = new Socket("10.0.0.135",8080);
sck.setKeepAlive(true);
screenConfig();
in = new BufferedReader(new InputStreamReader(sck.getInputStream()));
out = new PrintWriter(sck.getOutputStream());
sendDataWithString("testing 1 2 3");
int charsRead = 0;
char[] buffer = new char[BUFFER_SIZE];
while ((charsRead = in.read(buffer)) != -1) {
response += new String(buffer).substring(0, charsRead);
handler.post( updateUI );
}
screenConfig();
}
}
catch (IOException e) {
System.out.print(e+"");
}
catch (Exception e) {
System.out.print(e+"");
}
}
}).start();
}
public void screenConfig(){
if (sck.isClosed() == false){
textOut.setClickable(true);
btnSend.setClickable(true);
btnDisconnect.setClickable(true);
btnConnect.setClickable(false);
}else{
textOut.setClickable(false);
btnSend.setClickable(false);
btnDisconnect.setClickable(false);
btnConnect.setClickable(true);
}
}
public void SendMessage(View view){
sendDataWithString(textOut.getText().toString());
textOut.setText(null);
}
public void DisConnect(View view){
CloseConnection();
}
public void CloseConnection(){
if (sck != null) {
try {
sck.close();
screenConfig();
} catch (IOException e) {
e.printStackTrace();
} finally {
sck = null;
}
}
}
public void sendDataWithString(String message) {
if (message != null && sck != null) {
out.write(message);
out.flush();
}
}
}

android quiz help

So I've decided to to teach myself how to program for android and have a general understanding for java. Well i decided to borrow someones code from the internet and utilize it to assist in creating my first quiz app. I am getting some errors in this code and was wondering if anyone would be so kind to assist me. Thanks
Code:
package com.danyluk.MedicStudyGuide;
import java.io.IOException;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
public class Quiz extends Activity{
/** Called when the activity is first created. */
private RadioButton radioButton;
private TextView quizQuestion;
private TextView tvScore;
private int rowIndex = 1;
private static int score=0;
private int questNo=0;
private boolean checked=false;
private boolean flag=true;
private RadioGroup radioGroup;
String[] corrAns = new String[5];
final DataBaseHelper db = new DataBaseHelper(this);
Cursor c1;
Cursor c2;
Cursor c3;
int counter=1;
String label;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.quiz);
String options[] = new String[19];
// get reference to radio group in layout
RadioGroup radiogroup = (RadioGroup) findViewById(R.id.rdbGp1);
// layout params to use when adding each radio button
LinearLayout.LayoutParams layoutParams = new RadioGroup.LayoutParams(
RadioGroup.LayoutParams.WRAP_CONTENT,
RadioGroup.LayoutParams.WRAP_CONTENT);
try {
db.createDataBase();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
c3 = db.getCorrAns();
tvScore = (TextView) findViewById(R.id.tvScore);
for (int i=0;i<=4;i++)
{
corrAns[i]=c3.getString(0);
c3.moveToNext();
}
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.rdbGp1);
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
for(int i=0;;){
RadioButton btn = (RadioButton) radioGroup.getChildAt(i);
String text;
if (btn.isPressed() && btn.isChecked() && questNo < 5)
{
Log.e("corrAns[questNo]",corrAns[questNo]);
if (corrAns[questNo].equals(btn.getText()) && flag==true)
{
score++;
flag=false;
checked = true;
}
else if(checked==true)
{
score--;
flag=true;
checked = false;
}
}
}
tvScore.setText = ("Score: " + Integer.toString(score) + "/5");
Log.e("Score:", Integer.toString(score));
}
});
quizQuestion = (TextView) findViewById(R.id.TextView01);
displayQuestion();
/*Displays the next options and sets listener on next button*/
Button btnNext = (Button) findViewById(R.id.btnNext);
btnNext.setOnClickListener(btnNext_Listener);
/*Saves the selected values in the database on the save button*/
Button btnSave = (Button) findViewById(R.id.btnSave);
btnSave.setOnClickListener(btnSave_Listener);
}
/*Called when next button is clicked*/
private View.OnClickListener btnNext_Listener= new View.OnClickListener() {
@Override
public void onClick(View v) {
flag=true;
checked = false;
questNo++;
if (questNo < 5)
{
c1.moveToNext();
displayQuestion();
}
}
};
/*Called when save button is clicked*/
private View.OnClickListener btnSave_Listener= new View.OnClickListener() {
@Override
public void onClick(View v) {
}
};
private void displayQuestion()
{
//Fetching data quiz data and incrementing on each click
c1=db.getQuiz_Content(rowIndex);
c2 =db.getAns(rowIndex++);
quizQuestion.setText(c1.getString(0));
radioGroup.removeAllViews();
for (int i=0;i<=3;i++)
{
//Generating and adding 4 radio buttons dynamically
radioButton = new RadioButton(this);
radioButton.setText(c2.getString(0));
radioButton.setId(i);
c2.moveToNext();
radioGroup.addView(radioButton);
}
}}}
You forgot give us the error that you get

Help skipping line in loading text from the internet.

I am trying to create a simple android app that loads a text file from the internet and displays in a scrollable view. I got the text file to load just fine but I cant seem to figure out how to get it to skip lines using the traditional "/n"
Here is my code:
Code:
package com.brooksytech.ykyacw;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class ViewSubmissions extends Activity{
TextView textMsg;
final String textSource = "http://www.fake.com/fake.txt";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewsubmissions);
textMsg = (TextView)findViewById(R.id.textmsg);
URL textUrl;
try {
textUrl = new URL(textSource);
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(textUrl.openStream()));
String StringBuffer;
String stringText = "";
while ((StringBuffer = bufferReader.readLine()) != null) {
stringText += StringBuffer;
}
bufferReader.close();
textMsg.setText(stringText);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
textMsg.setText(e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
textMsg.setText(e.toString());
}
}
}
Supposedly this code is similar to what I want to do but I dont know how to implement it correctly:
Code:
public static String readRawTextFile(Context ctx, int resId)
{
InputStream inputStream = ctx.getResources().openRawResource(resId);
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
StringBuilder text = new StringBuilder();
try {
while (( line = buffreader.readLine()) != null) {
text.append(line);
text.append('\n');
}
} catch (IOException e) {
return null;
}
return text.toString();
}
All I want it to do is skip a line when it sees /n
Thanks for the help!
brooksyx said:
All I want it to do is skip a line when it sees /n
Thanks for the help!
Click to expand...
Click to collapse
what output are you getting? what does it show. do the "\n"'s show up?
i have this sorta thing in a java app of mine with much the same code.
what are you trying to parse?
Pvy.
Please use the Q&A Forum for questions &
Read the Forum Rules Ref Posting
Thanks ✟
Moving to Q&A

Q> HELP Connection andrdoid to pc Programming

this is my server code
i am getting an error on my android phone when i clicked the device address
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.bluetooth.*;
import javax.microedition.io.*;
public class ServerSide {
//private static LocalDevice localDevice;
static LocalDevice localDevice;
DiscoveryAgent agent;
private void startServer() throws IOException{
UUID uuid = new UUID("112f8dbf1e46442292b6796539467bc9", false);
String connectionString = "btspp://localhost:" + uuid
+";name=SampleSPPServer";
//open server url
StreamConnectionNotifier streamConnNotifier =
(StreamConnectionNotifier)Connector.open( connectionString );
System.out.println("\nServer Started. Waiting for clients to
connect...");
StreamConnection connection=streamConnNotifier.acceptAndOpen();
RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
System.out.println("Remote device address:
"+dev.getBluetoothAddress());
System.out.println("Remote device name:
"+dev.getFriendlyName(true));
}
public static void main(String[] args) {
//display local device address and name
try{
localDevice = LocalDevice.getLocalDevice();
System.out.println("Address: "+localDevice.getBluetoothAddress());
System.out.println("Name: "+localDevice.getFriendlyName());
}catch(Exception e){
System.err.println(e.toString());
System.err.println(e.getStackTrace());
e.printStackTrace();}
try{
ServerSide sampleSPPServer=new ServerSide();
sampleSPPServer.startServer();
}catch(Exception e){
System.err.println(e.toString());
System.err.println(e.getStackTrace());
e.printStackTrace();}
}
}
**************************************************************
and this is my client(android) code
package client.side;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ClientSideActivity extends Activity {
int REQUEST_ENABLE_BT = 0;
private BluetoothAdapter mBluetoothAdapter;
private ArrayAdapter<String> mArrayAdapter;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn1 = (Button)findViewById(R.id.button1);
Button btn2 = (Button)findViewById(R.id.button2);
final ListView lv1 = (ListView)findViewById(R.id.listView1);
final TextView out = (TextView)findViewById(R.id.textView1);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mArrayAdapter = new
ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent,
REQUEST_ENABLE_BT);
}
out.setText(null);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
out.setText("Paired Devices");
Set<BluetoothDevice> pairedDevices =
mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0){
for(BluetoothDevice device : pairedDevices){
mArrayAdapter.add(device.getName() + "\n" +
device.getAddress());
}
}
lv1.setAdapter(mArrayAdapter);
}
});
btn2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
out.setText("Discovered Devices");
mBluetoothAdapter.startDiscovery();
Toast msg = Toast.makeText(ClientSideActivity.this, "Discovering
Devices please wait.", Toast.LENGTH_LONG);
msg.show();
final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device =
intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show
in a ListView
mArrayAdapter.add(device.getAddress());
} }
};
// Register the BroadcastReceiver
IntentFilter filter = new
IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister
during onDestroy
}
});
lv1.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0, View arg1, int
position,long id)
{
out.setText(arg0.getItemAtPosition(position).toString());
BluetoothDevice remoteDev = (BluetoothDevice)
arg0.getItemAtPosition(position);
ConnectThread conDev = new ConnectThread(remoteDev);
conDev.start();
}
});
}
public class ConnectThread extends Thread {
private final UUID MY_UUID =
UUID.fromString("112f8dbf1e46442292b6796539467bc9");
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to
mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
try {
// MY_UUID is the app's UUID string, also used by the
server code
tmp =
device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the
connection
mBluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will
block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate
thread)
}
/** Will cancel an in-progress connection, and close the
socket */
}
}

[Q] How can put my own textview in this coding

Hello everyone I want to put my own textview or edittext in canvas1.java or canvasclass.java . Actually this coding are lipitk toolkit handwriting recognition android application. Please help me if possible.
/************************canvas1.java*********************/
package com.canvas;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.inputmethodservice.InputMethodService;
import android.opengl.Visibility;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Scroller;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.LinearLayout.LayoutParams;
import com.google.tts.TTS;
public class Canvas1 extends Activity implements OnClickListener,OnLongClickListener{
private TTS myTts;
CanvasClass canClass;
private LinearLayout main;
private LinearLayout cenerLayout;
private LinearLayout topLayout;
private LinearLayout subLayout;
private LinearLayout tvLayout;
private LinearLayout SecondLayout;
private LinearLayout mylayout;
private ImageView Exit;
private ScrollView scrllView;
private HorizontalScrollView HorizontalSV;
private TextView[] TV=new TextView[1];
private TextView[] s=new TextView[1];
private TextView[] TViews=new TextView[5];
public final static int mButtonHeight = 220;
public final static int mButtonWidth = 80;
String inst[]=new String[5]; ;
String InstTemp;
int flag=0;
int c0flag=0;
int c1flag=0;
int c2flag=0;
int c3flag=0;
int SpaceSelFlag = 1;
String newStr="";
int height;
public static int width;
Vibrator v;
/** Called when the activity is first created. */
CanvasClass canvasClass = null;
Canvas1 conObj = null;
public final int MY_DATA_CHECK_CODE = 1;
private TextToSpeech mTts = null;
public ProgressDialog dialog;
@override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
width = display.getWidth();
height = display.getHeight();
v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
AssetInstaller assetInstaller = new AssetInstaller(getApplicationContext(), "projects");
try {
assetInstaller.execute();
} catch (IOException e) {
e.printStackTrace();
}
conObj = this;
canvasClass = new CanvasClass(this,conObj);
main = new LinearLayout(this);
main.setOrientation(LinearLayout.VERTICAL);
main.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.FILL_PARENT));
topLayout = new LinearLayout(this);
topLayout.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
((height/2)+130)));
topLayout.setOrientation(LinearLayout.VERTICAL);
topLayout.setBackgroundColor(0xffffffcc);
topLayout.addView(canvasClass);
/*
mylayout = new LinearLayout(this);
mylayout.setOrientation(LinearLayout.VERTICAL);
mylayout.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
mylayout.setBackgroundColor(Color.WHITE);
for(int i = 0; i <s.length; i++) {
s = new EditText(this);
s.setTextColor(Color.RED);
s.setTextSize(40);
s.setGravity(Gravity.AXIS_Y_SHIFT);
s.setTypeface(null, Typeface.BOLD);
s.setHeight(height/8);
s.setPadding(5, 0, 0, 0);
s.setScroller(new Scroller(this));
s.setVerticalScrollBarEnabled(true);
s.setMovementMethod(ScrollingMovementMethod.getInstance());
mylayout.addView(s);
}
*/
cenerLayout = new LinearLayout(this);
cenerLayout.setOrientation(LinearLayout.VERTICAL);
cenerLayout.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
cenerLayout.setBackgroundColor(Color.GREEN);
for(int i = 0; i <TV.length; i++) {
TV = new TextView(this);
TV.setTextColor(Color.RED);
TV.setTextSize(40);
TV.setGravity(Gravity.CENTER_HORIZONTAL);
TV.setTypeface(null, Typeface.BOLD);
TV.setHeight(height/8);
TV.setPadding(5, 0, 0, 0);
TV.setScroller(new Scroller(this));
TV.setVerticalScrollBarEnabled(true);
TV.setMovementMethod(ScrollingMovementMethod.getInstance());
cenerLayout.addView(TV);
}
SecondLayout = new LinearLayout(this);
SecondLayout.setOrientation(LinearLayout.VERTICAL);
SecondLayout.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
70));
SecondLayout.setBackgroundColor(0xff26466D);
tvLayout = new LinearLayout(this);
tvLayout.setOrientation(LinearLayout.HORIZONTAL);
tvLayout.setLayoutParams(new LinearLayout.LayoutParams(
(width-20),
((height/8)-30)));
for(int i = 0; i < TViews.length; i++) {
TViews = new TextView(this);
TViews.setTextColor(Color.YELLOW);
TViews[0].setText("Suggested words..");
TViews[0].setTextColor(0xffE8E8E8);
TViews.setTextSize(15);
TViews.setGravity(Gravity.CENTER);
TViews.setPadding(10, 0, 0, 0);
TViews.setHeight(((height/8)-30));
TViews.setOnClickListener(this);
tvLayout.addView(TViews);
}
HorizontalSV=new HorizontalScrollView(this);
HorizontalSV.setLayoutParams(new LinearLayout.LayoutParams(
(width-125),
LinearLayout.LayoutParams.WRAP_CONTENT));
HorizontalSV.addView(tvLayout,new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
SecondLayout.addView(HorizontalSV);
subLayout = new LinearLayout(this);
subLayout.setOrientation(LinearLayout.HORIZONTAL);
subLayout.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
((height/8)-16)));
subLayout.setGravity(Gravity.BOTTOM);
Exit = new ImageView(this);
Exit.setImageResource(R.drawable.exit);
Exit.setPadding(30, 0, 0, 0);
Exit.setOnClickListener(this);
subLayout.addView(Exit);
main.addView(cenerLayout);
main.addView(topLayout);
main.addView(subLayout);
setContentView(main);
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
}
protected void onActivityResult(
int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
// success, create the TTS instance
mTts = new TextToSpeech(this, new OnInitListener() {
public void onInit(int status) {
// TODO Auto-generated method stub
//mTts.speak("Hello World", TextToSpeech.QUEUE_FLUSH, null);
}
});
} else {
// missing data, install it
Intent installIntent = new Intent();
installIntent.setAction(
TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
}
}
public void onClick(View v) {
if(v==Exit){
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
}
}
/* This method will handle the swipe across the edge. Calls Freepad once the
touch area reaches the right end of screen */
public void ClearCanvas(){
if(canvasClass != null){
topLayout.removeView(canvasClass);
canvasClass = new CanvasClass(this,conObj);
topLayout.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
((height/2)+130)));
topLayout.addView(canvasClass);
}
}
class ProgressdialogClass extends AsyncTask<Void, Void, String> {
@override
protected String doInBackground(Void... unsued) {
canvasClass.addStroke(canvasClass._currentStroke);
return null;
}
@override
protected void onPostExecute(String sResponse) {
dialog.dismiss();
FreePadCall();
}
@override
protected void onPreExecute(){
dialog = ProgressDialog.show(Canvas1.this, "Processing","Please wait...", true);
}
}
public void CallingMethod(){
ProgressdialogClass ObjAsy=new ProgressdialogClass();
ObjAsy.execute();
}
public void FreePadCall(){
HorizontalSV.setVisibility(View.VISIBLE);
if(canvasClass != null){
topLayout.removeView(canvasClass);
canvasClass.destroyDrawingCache();
canvasClass = new CanvasClass(this,conObj);
topLayout.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
((height/2)+130)));
topLayout.addView(canvasClass);
}
TV[0].setText(canvasClass.character[0]);
String str1 = TV[0].getText().toString();
mTts.speak(str1, 0, null);
}
public boolean onLongClick(View v) {
System.out.println("-----long click------");
return true;
}
int curr_indx = 0;
public void SpeakOutChoices(){
if(canvasClass != null){
topLayout.removeView(canvasClass);
canvasClass = new CanvasClass(this,conObj);
topLayout.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
((height/2)+130)));
topLayout.addView(canvasClass);
}
System.out.println("index"+curr_indx +"---"+ CanvasClass.StrokeResultCount);
if(curr_indx < CanvasClass.StrokeResultCount){
TV[0].setText(CanvasClass.character[curr_indx]);
String Choice1=CanvasClass.character[curr_indx];
mTts.speak(Choice1, 0, null);
curr_indx++;
if(curr_indx == CanvasClass.StrokeResultCount)
curr_indx = 0;
}
}
}
/***************Convasclass.java*******************/
package com.canvas;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import com.canvas.Canvas1.ProgressdialogClass;
import android.R.color;
import android.R.style;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.PointF;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.os.CountDownTimer;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.WindowManager;
import android.view.View;
import android.view.View.OnTouchListener;
public class CanvasClass extends View implements OnTouchListener{
private LipiTKJNIInterface _lipitkInterface;
private LipiTKJNIInterface _recognizer;
private Page _page;
private PointF _lastSpot;
public Stroke _currentStroke;
private ArrayList<PointF> _currentStrokeStore;
private ArrayList<Stroke> _strokes;
private Stroke[] _recognitionStrokes;
private ArrayList<Symbol> _symbols;
public static String[] character;
public static int StrokeResultCount=0;
ArrayList<Values> vals = new ArrayList<Values>();
public static int min=480;
public static int max=0;
public static int minX=800;
public static int maxX=0;
public static int XCood=0;
private int mPosX;
private int mPosY;
private int mLastTouchX=0;
private int mLastTouchY=0;
boolean flag=true;
boolean flagbs=true;
public static boolean canvastest=true;
MyCount counter;
MyLongPressCount myLongPress;
BufferedWriter out;
Canvas1 canObj=null;
private static final String TAG = "DrawView";
public CanvasClass(Context context,Canvas1 canObjParam) {
super(context);
canObj=canObjParam;
globalvariable.paint=new Paint();
setFocusable(true);
setFocusableInTouchMode(true);
this.setOnTouchListener(this);
globalvariable.paint.setColor(Color.BLUE);
globalvariable.paint.setAntiAlias(true);
globalvariable.paint.setDither(true);
globalvariable.paint.setStyle(Paint.Style.STROKE);
globalvariable.paint.setStrokeJoin(Paint.Join.ROUND);
globalvariable.paint.setStrokeCap(Paint.Cap.ROUND);
globalvariable.paint.setStrokeWidth(5);
counter = new MyCount(700,1000);
myLongPress = new MyLongPressCount(3000,1000);
_currentStroke = new Stroke();
_strokes = new ArrayList<Stroke>();
_recognizer = null;
_symbols = new ArrayList<Symbol>();
// Initialize lipitk
Context contextlipi = getContext();
File externalFileDir = contextlipi.getExternalFilesDir(null);
String path = externalFileDir.getPath();
Log.d("JNI", "Path: " + path);
_lipitkInterface = new LipiTKJNIInterface(path, "SHAPEREC_ALPHANUM");
_lipitkInterface.initialize();
_page = new Page(_lipitkInterface);
_recognizer=_lipitkInterface;
}
public boolean onTouch(View view, MotionEvent event) {
Values vs=new Values();
final int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN: {
min=480;
max=0;
maxX=0;
minX=800;
counter.cancel();
myLongPress.start();
globalvariable.IsUserWriting=true;
vs.x = (int) event.getX();
vs.y = (int) event.getY();
float X= (float) vs.x;
float Y= (float) vs.y;
PointF p = new PointF(X, Y);
_lastSpot=p;
_currentStroke.addPoint(p);
if(vs.y>max)
max=vs.y;
if(vs.y<min)
min=vs.y;
if(vs.x>maxX)
maxX=vs.x;
if(vs.x<minX)
minX=vs.x;
XCood=vs.x;
globalvariable.strokeXY += "{" + vs.x + "," + vs.y + "}|";
vals.add(vs);
invalidate();
System.out.println("action down stroke values===");
break;
}
case MotionEvent.ACTION_MOVE: {
counter.cancel();
vs.x = (int) event.getX();
vs.y = (int) event.getY();
float X= (float) vs.x;
float Y= (float) vs.y;
PointF p = new PointF(X, Y);
_lastSpot=p;
_currentStroke.addPoint(p);
//myLongPress.cancel();
globalvariable.VSG=vs.x;
globalvariable.LongPressFlag=true;
globalvariable.strokeXY += "{" + vs.x + "," + vs.y + "}|";
vals.add(vs);
if(vs.y>max)
max=vs.y;
if(vs.y<min)
min=vs.y;
if(vs.x>maxX)
maxX=vs.x;
if(vs.x<minX)
minX=vs.x;
XCood=vs.x;
System.out.println("action move stroke values===");
invalidate();
break;
}
case MotionEvent.ACTION_UP:{
vs.x = (int) event.getX();
vs.y = (int) event.getY();
float X= (float) vs.x;
float Y= (float) vs.y;
PointF p = new PointF(X, Y);
_lastSpot=p;
_currentStroke.addPoint(p);
_currentStrokeStore = new ArrayList<PointF>();
_currentStrokeStore.add(p);
System.out.println("Max==="+max);
System.out.println("Min==="+min);
globalvariable.strokeXY += "N";
/* this condition should be checked only once for the first stroke after
a time out */
if(globalvariable.isFirststroke)
{
if((max-min) < 30 &&(max!=min))
{
globalvariable.IsUserWriting = false;
}
}
if(globalvariable.isFirststroke && globalvariable.IsUserWriting == false)
{
globalvariable.isFirststroke = true;
}
else
{
globalvariable.isFirststroke = false;
}
if(globalvariable.IsUserWriting)
{
counter.start();
}
else
{
if(XCood < 30)
{
//canObj.backspace();
}
else if(XCood > (canObj.width - 30))
{
canObj.SpeakOutChoices();
}
}
myLongPress.cancel();
System.out.println("action up stroke values===");
break;
}
}
return true;
}
public void addStroke(Stroke stroke) {
_strokes.add(stroke);
_recognitionStrokes = new Stroke[_strokes.size()];
for (int s = 0; s < _strokes.size(); s++)
_recognitionStrokes = _strokes.get(s);
LipitkResult[] results = _recognizer.recognize(_recognitionStrokes);
for (LipitkResult result : results) {
Log.e("jni", "ShapeID = " + result.Id + " Confidence = " + result.Confidence);
}
String configFileDirectory = _recognizer.getLipiDirectory() + "/projects/alphanumeric/config/";
character=new String[results.length];
for(int i=0;i<character.length;i++){
character = _recognizer.getSymbolName(results.Id, configFileDirectory);
}
StrokeResultCount=results.length;
_recognitionStrokes = null;
}
public void clearCanvas(){
System.out.println("====inside clearcanvas====");
canvasCpy.drawColor(Color.BLUE);
System.out.println("====over clearcanvas====");
}
public static Canvas canvasCpy = null;
int canvasWidth = 0;
int canvasHeight = 0;
private Bitmap bitmap;
@override
protected void onDraw(Canvas canvas) {
canvasHeight=canvas.getHeight();
canvasWidth=canvas.getWidth();
for (Values values : vals) {
canvas.save();
canvas.drawPoint(values.x, values.y, globalvariable.paint);
canvas.restore();
mLastTouchX=values.x;
mLastTouchY=values.y;
}
File root = android.os.Environment.getExternalStorageDirectory();
File file = new File(root, "Freepad/points.txt");
if(!(file.isDirectory()))
{
return;
}
else
{
try {
out = new BufferedWriter(new FileWriter(file));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out.write(globalvariable.strokeXY);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
globalvariable.canvasvar=canvas;
System.out.println("stroke values:-------"+globalvariable.strokeXY);
System.out.println("stroke values:-------"+globalvariable.strokeXY.length());
}
}
public class MyCount extends CountDownTimer{
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@override
public void onFinish() {
System.out.println("Timer Flag :: " + globalvariable.TimerFlag);
if(globalvariable.LongPressFlag){
canObj.CallingMethod();
globalvariable.IsUserWriting=false;
globalvariable.isFirststroke = true;
}
else{
}
}
@override
public void onTick(long millisUntilFinished) {
System.out.println("Tick tick Flag :: " + globalvariable.TimerFlag);
}
}
public class MyLongPressCount extends CountDownTimer{
public MyLongPressCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@override
public void onFinish() {
globalvariable.LongPressFlag=false;
System.out.println("Long press timer expiry: Timer Flag :: " + globalvariable.TimerFlag);
canObj.ClearCanvas();
}
@override
public void onTick(long millisUntilFinished) {
System.out.println("Tick tick Flag :: " + globalvariable.TimerFlag);
}
}
}
class Values {
int x, y;
@override
public String toString() {
return x + ", " + y;
}
}

Categories

Resources