Related
Hi I am stuck while i was trying to control 8x8 led matrix by cascading two 74hc595 shift registers. I had build the circuit and the program, which I am including here. It's actually giving me the right output. But the major problem is visible flickering. Can somebody guide me what can i do to remove the flickering?
public class MainActivity extends Activity {
private static final String SR_SRCLK_PIN = "BCM27"; //clock pins shcp
private static final String SR_RCLK_PIN = "BCM18"; //latch pin stcp
private static final String SR_SDI_PIN = "BCM17"; //data pin
private static final String TAG = "MAT21";
private Gpio mRCLK;
private Gpio mSRCLK;
private Gpio mSDI;
private int charSeq=0;
int data[]=
{
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, //NULL
0x00,0x00,0x3C,0x42,0x42,0x3C,0x00,0x00, //0
0x00,0x00,0x00,0x44,0x7E,0x40,0x00,0x00, //1
0x00,0x00,0x44,0x62,0x52,0x4C,0x00,0x00, //2
0x00,0x00,0x78,0x14,0x12,0x14,0x78,0x00, //A
0x00,0x00,0x60,0x90,0x90,0xFE,0x00,0x00, //d
0x00,0x00,0x1C,0x2A,0x2A,0x2A,0x24,0x00, //e
0x00,0x00,0x7E,0x12,0x12,0x0C,0x00,0x00, //p
0x00,0x00,0x08,0x7E,0x88,0x40,0x00,0x00, //t
0x3C,0x42,0x95,0xB1,0xB1,0x95,0x42,0x3C, //:)
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PeripheralManagerService pms = new PeripheralManagerService();
try {
mRCLK = pms.openGpio(SR_RCLK_PIN);
mRCLK.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);
mSRCLK = pms.openGpio(SR_SRCLK_PIN);
mSRCLK.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);
mSDI = pms.openGpio(SR_SDI_PIN);
mSDI.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);
} catch (IOException e) {
Log.e(TAG, "Error on PeripheralIO API", e);
}
try {
thread.start();
while (true){
Thread.sleep(2000);
charSeq++;
if(charSeq==10){
charSeq=0;
}
}
} catch (Exception sd) {
}
}
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
while (true) {
for (int rowNum = 0; rowNum < 8; rowNum++) {
mRCLK.setValue(false);
shiftOut(data[(charSeq * 8) + rowNum],rowNum);
mRCLK.setValue(true);
}
}
}catch (Exception ex){
}
}
});
#Override
protected void onDestroy() {
super.onDestroy();
// Clean all resources
if (mSDI != null) {
try {
mSDI.setValue(false);
mSDI.close();
} catch (IOException e) {
Log.e(TAG, "Error on PeripheralIO API", e);
}
}
if (mRCLK != null) {
try {
mRCLK.setValue(false);
mRCLK.close();
} catch (IOException e) {
Log.e(TAG, "Error on PeripheralIO API", e);
}
}
if (mSRCLK != null) {
try {
mSRCLK.setValue(false);
mSRCLK.close();
} catch (IOException e) {
Log.e(TAG, "Error on PeripheralIO API", e);
}
}
}
void shiftOut(int data, int rowNum) {
try {
for (int i = 7; i >= 0; i--) {
mSRCLK.setValue(false);
mSDI.setValue((((data >> i) & 1) == 0));
mSRCLK.setValue(true);
}
for (int i = 0; i <8; i++) {
mSRCLK.setValue(false);
mSDI.setValue(i==rowNum?true:false);
mSRCLK.setValue(true);
}
} catch (Exception sd) {
}
}
}
Schemetic Diagram
It's not entirely clear from your question what clock frequency you need to achieve to drive your matrix display properly, but regardless it's unlikely you will be able to get there bit-banging the GPIO in this fashion. The flickering you see is probably because the I/O is not toggling fast enough in your code.
I would recommend moving to an external hardware controller for your display (something like the MAX7219, for example) that you can control over a serial port like I2C or SPI.
I recently created an activity in my app. Now I wanted the user to download a .pdf file when he/she wants to view the guidelines. I wanted to implement this on a button. Any idea how to do this properly?
Heres my code below:
public class Exhibitor_Registration_Activity extends AppCompatActivity {
Button buttonDownload;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exhibitor_registration_);
this.setTitle("Buyer Registration");
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
myToolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
final Button buttonDownload = (Button) findViewById(R.id.buttonDownload);
buttonDownload.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
try {
//this is the file you want to download from the remote server
String path ="http://www.manilafame.com/website-assets/downloads/exhibitor-application-kit/local/201704/1-Summary-of-Participation-Details-April-2017_MN_002.pdfp";
//this is the name of the local file you will create
String targetFileName = null;
boolean eof = false;
URL u = new URL(path);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
FileOutputStream f = new FileOutputStream(new File("c:\\junk\\"+targetFileName));
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ( (len1 = in.read(buffer)) > 0 ) {
f.write(buffer,0, len1);
}
f.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
I also got the source code from here and here.
if you want resumable, speed of download ...
follow this steps
create a class DownloadManager.java
public class DownloadManager extends AsyncTask<String,String,String>{
String downloadlink,fileDestination;
public static final int ON_INIT=100,ON_ERROR=102,ON_PROGRASS=103,ON_COMPLETED=104,STATUS_DOWNLOADED=1500,STATUS_NOT_YET=1501;
private onUpdateListener onUpdateListener;
private String downloadedPath="";
private long downloaded=0;
private File file;
private String returnData=null;
private File cacheDownloadFile;
public DownloadManager(String downloadlink,String fileDestinationPath){
this.downloadlink=downloadlink;
this.fileDestination=fileDestinationPath;
file=new File(fileDestination, Tools.getFileName(downloadlink));
cacheDownloadFile=new File(AppCostants.CHACHE_PATH+Tools.getFileName(downloadlink));
try {
if(cacheDownloadFile.isFile())
downloaded=Tools.getFileSize(cacheDownloadFile);
else
downloaded=0;
Log.d("FILE_DOWNLOAD_TAG_p",downloaded+" <- "+cacheDownloadFile.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
fireOnUpdate(ON_INIT,"init ...");
}
#Override
protected String doInBackground(String... params) {
try {
File dir=new File(fileDestination);
File chacheDir=new File(AppCostants.CHACHE_PATH);
if(!chacheDir.isDirectory())
chacheDir.mkdirs();
if(!dir.isDirectory()){
dir.mkdirs();
}
if(file.exists()) {
Log.d("FILE_DOWNLOAD_TAG","File exist return complete");
return "COMPLETED";//file exist
}
if(!cacheDownloadFile.exists()){
cacheDownloadFile.createNewFile();
}
Log.d("FILE_DOWNLOAD_TAG","LINK "+downloadlink);
URL url=new URL(downloadlink);
HttpURLConnection urlConnection= (HttpURLConnection) url.openConnection();
if(downloaded>0)
urlConnection.setRequestProperty("Range","byte="+downloaded);
urlConnection.connect();
int status = urlConnection.getResponseCode();
InputStream inputStream=urlConnection.getInputStream();
int totalSize=urlConnection.getContentLength();
if(totalSize<=downloaded){
returnData= "COMPLETED";
publishProgress("File checked "+Tools.getFileName(file.getAbsolutePath()));
return returnData;
}
this.downloadedPath=cacheDownloadFile.getAbsolutePath();
byte[] buffer=new byte[1024];
int bufferLength=0;
FileOutputStream fileOutput=new FileOutputStream(cacheDownloadFile);
long d=0;
long starttime=System.currentTimeMillis();
while ((bufferLength=inputStream.read(buffer))>0){
fileOutput.write(buffer,0,bufferLength);
downloaded+=bufferLength;
d+=bufferLength;
//String l=" "+Tools.getFileName(file.getAbsolutePath())+" ( "+Tools.convertMemory(downloaded)+" / "+Tools.convertMemory(totalSize)+" )";
String l=" "+Tools.convertMemory(downloaded)+" / "+Tools.convertMemory(totalSize)+" ( "+getDownloadSpeed(starttime,d)+" )";
publishProgress(l);
if(downloaded>=totalSize){
break;
}
}
Log.d("FILE_DOWNLOAD_TAG","DWONLOADED TO "+downloadedPath+" ("+cacheDownloadFile.length()+")");
fileOutput.close();
if(Tools.fileCopy(file,cacheDownloadFile)){
Log.d("FILE_DOWNLOAD_TAG","file Copied, delete cache");
cacheDownloadFile.delete();
}
returnData="COMPLETED";
} catch (MalformedURLException e) {
returnData=null;
e.printStackTrace();
publishProgress(e.toString());
Log.d("###################",e+"");
} catch (IOException e) {
returnData=null;
e.printStackTrace();
publishProgress(e.toString());
}
return returnData;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
fireOnUpdate(ON_PROGRASS,values[0]);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(s!=null){
fireOnUpdate(ON_COMPLETED,downloadedPath);
}else{
fireOnUpdate(ON_ERROR,"Download failed");
}
}
public interface onUpdateListener{
void onUpdate(int code,String message);
}
public void setOnUpdateListener(onUpdateListener onUpdateListener){
this.onUpdateListener=onUpdateListener;
}
private void fireOnUpdate(int code,String message){
if(onUpdateListener!=null)
onUpdateListener.onUpdate(code,message);
}
private String getDownloadSpeed(long starttime,float totalDownloaded) {
long elapsedTime = System.currentTimeMillis() - starttime;
//byte :
float speed=1000f * totalDownloaded / elapsedTime;
return convert(speed);
}
private String convert(float value){
long kb=1024
,mb=kb*1024
,gb=mb*1024;
if(value<kb){
String speed=(value+"");
speed=speed.substring(0,speed.indexOf('.')+2);
return speed+" B/s";
}else if(value<mb){
value=value/kb;
String speed=(value+"");
speed=speed.substring(0,speed.indexOf('.'));
return (speed)+" KB/s";
}else if(value<gb){
value=(value/mb);
String speed=(value+"");
speed=speed.substring(0,speed.indexOf('.'));
return speed+" MB/s";
}
return "";
}
}
use this code in onClick()
DownloadManager downloadManager = new DownloadManager(url,filepath);
set event
downloadManager.setOnUpdateListener(new DownloadManager.onUpdateListener() {
#Override
public void onUpdate(int code, String message) {
if (code == DownloadManager.ON_COMPLETED) {
}
if(DownloadManager.ON_PROGRASS==code){}
}
});
start download by
downloadManager.execute();
lib setup
compile "commons-io:commons-io:+"
Tools.java
public static long getFileSize(File file) throws IOException {
FileOutputStream fileOutputStream=new FileOutputStream(file);
fileOutputStream.close();
return file.length();
}
public static boolean fileCopy(File dest,File source){
try {
FileUtils.copyFile(source,dest);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
It is really bad idea to download file in main thread.
Use separate Thread for this
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
//your downloading here
}
});
thread.start();
it`s better, but still not so good. There are some problems with it:
1) User know nothing about downloading
So better to show additional layout which overlays screen with progress bar, probably indeterminate if you want to write less code. Then after downloading is finished you just hide your layout.
You can use runOnUiThread inside run method in thread for it.
runOnUiThread(new Runnable() {
#Override
public void run() {
//just hide some popup
//or do what you want after downloading is finished
popupLayout.serVisibility(View.GONE);
}
});
2) If user will do action which re-creates activity/fragment (like changing screen orientaion) with running thread you will get memory leak and probably activity will not know about end of download.
There are few ways to solve this problem:
You can block screen orientation at this screen, at least while downloading. Probably easiest way in your case.
You can use downloading in foreground service. Its really good
practice, but you will have to learn about services.
You can try to interrupt downloading by calling thread.interrupt()
method in onDestroy of your Activity/Fragment
You can use something like rxJava/rxAndroid (so you don not use threads at all, but you need some time for learn rxJava)
UPD
About threads
Not so bad tutorial about threads in android
You can use AsyncTask instead of Thread, but I highly recommend to use threads especially for long operations.
I have server client communication program at server side I have camera and that camera I am controlling by my android application as client it is working but the problem is when the server memory is full then server is stopping the camera and sending a message to client and and if client want to stop camera by it self then client is sending command to server and server stop the camera .
The problem is there only I am not getting the massage if I am getting the massage of "memory full" then I am not getting the massage "stopping camera "when user want to kill by itself and if am manage to get the "stopping camera " message then I am not getting the "memory full massage "
here is my code please help me
thanks in advance
/** here is the recording start button I am calling a asyntask for recording
* Record and store video at battery control unit(server end) at background
*/
record=(ImageButton)findViewById(R.id.record);
record.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if(socket==null){
Toast.makeText(getApplicationContext(), "connection not establised", Toast.LENGTH_SHORT).show();
}
else{
pDialog.show();
suspended=false;
start=false;
new CommunicationTaskrec().execute();
}
}
});
/**
* Async task for the record, which runs on back ground.
*/
public class CommunicationTaskrec extends AsyncTask<Void, Void, String>{
#Override
protected String doInBackground(Void... params) {
String str = "3";
PrintWriter out = null;
try {
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
} catch (IOException e1) {
e1.printStackTrace();
}
out.println(str);
String resultrec="testing the UI Thread update";
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
try {
resultrec = in.readLine();
} catch (IOException e) {
e.printStackTrace();
}
//Log.d("inside bg thread", resultrec);
mHandler.obtainMessage(MESSAGE_READ, resultrec).sendToTarget();
out.flush();
// new Thread(new RecThread()).start();
// new CommunicationTaskmemorycheck().execute();
return resultrec;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
//here is the message handler case
/**
* Creating a dialog box which shows a timer for the recording time
*/
case MESSAGE_READ:
final String readBuf = (String) msg.obj;
String string1 ="no enough space left on device";
if(readBuf !=null){
if(readBuf.equalsIgnoreCase(string1))
{
pDialog.dismiss();
Toast.makeText(MainActivity.this, "NO Enough Space Left for Recording Please Remove some files at server end.", Toast.LENGTH_LONG).show();
}
else{
pDialog.dismiss();
Toast.makeText(MainActivity.this, readBuf, Toast.LENGTH_LONG).show();
//here is the dialog box where I have a stop button also by which user stopping the ///camera manually
View viewlist=MainActivity.this.getLayoutInflater().inflate(R.layout.timer, null);
dialog = new Dialog(MainActivity.this);
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
dialog.setContentView(viewlist);
dialog.setTitle("Status.....");
dialog.setCancelable(false);
TextView text = (TextView) dialog.findViewById(R.id.valuerec);
text.setText("Want to stop the Recording ?");
TextView cur_val = (TextView) dialog.findViewById(R.id.curvaluerec);
cur_val.setText("Recording Duration..");
Button stop = (Button) dialog.findViewById(R.id.start);
mChronometer = (Chronometer) dialog.findViewById(R.id.chronometer);
mChronometer.start();
dialog.show();
//here a asyntask and it is used for getting the memory full message
//it run contentiously on background and when the memory is full it //recieve "memory full massage"
task = new AsyncTask<Void, Void, Void>() {
String result=null;
protected Void doInBackground(Void... params) {
Runnable action = new Runnable() {
public void run() {
mHandler.obtainMessage(MESSAGE_READcreate, result).sendToTarget();
}
};
try {
do {
//Pause work if control is paused.
//tControl.waitIfPaused();
//Stop work if control is cancelled.
if (tControl.isCancelled()) {
suspended=true;
break;
}
while(!suspended){
String string1 ="memory full";
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
try {
result = in.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if((result!=null && result.equalsIgnoreCase(string1)) )
{
mHandler.obtainMessage(MESSAGE_READcreate, result).sendToTarget();
result=null;
suspended=true;
start=true;
runOnUiThread(action);
break;
}
}
}while (!suspended);
} catch (Exception e) {
}
return null;
}
};
task.execute();
//here is the dialog box stop button where I have a runnable thread which is used for send //command to server when user want to stop recording manually
stop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
task.cancel(true);
tControl.cancel();
suspended=true;
dialog.dismiss();
dialog=null;
mChronometer.stop();
pDialog.show();
//this is the runnable thread where I am getting "stopping //camera "massage
new Thread(new Runnable() {
#SuppressLint("ShowToast")
public void run() {
while (true) {
String str = "8";
PrintWriter out = null;
try {
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
} catch (IOException e) {
e.printStackTrace();
}
out.println(str);
String resultcap=null;
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
try {
resultcap = in.readLine();
} catch (IOException e) {
e.printStackTrace();
}
mHandler.obtainMessage(MESSAGE_READstoprunning, resultcap).sendToTarget();
out.flush();
//suspended=false;
break;
}
}
}
).start();
}
});
}
}
else{
pDialog.dismiss();
Toast.makeText(MainActivity.this, "error server not respondingrec", Toast.LENGTH_LONG).show();
}
break;
change execute() to executeOnExecutor(AsynTask.ThreadpoolExecutor)
AsyncTasks doc
When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.
If you truly want parallel execution, you can invoke
executeOnExecutor(java.util.concurrent.Executor, Object[])
with THREAD_POOL_EXECUTOR.
in my app I am trying to read a string out of a text file located online, and then save the contents to a variable. Here is my current code:
download.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
URL site = new URL("http://m.uploadedit.com/b029/1393133970157.txt");
Scanner s = new Scanner(site.openStream());
String num = s.nextLine();
}
catch(MalformedURLException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "String from file is: " + num,
Toast.LENGTH_LONG).show();
}
});
However this is giving me a force close. Here is the log: http://pastebin.com/2nsxmJz1
I believe that I need to implement an ASyncTask, but not sure how to go about doing so.
You can't use network communications on UI thread. As u correctly mentions you should use AsyncTask for such cases:
final AsyncTask<Object,Object,String> task = new AsyncTask<Object,Object,String>() {
protected String doInBackground(Object... o) {
try {
URL site = new URL("http://m.uploadedit.com/b029/1393133970157.txt");
Scanner s = new Scanner(site.openStream());
return s.nextLine();
}
catch(MalformedURLException e) {
throw new RuntimeException("Incorrect URL", e);
}
catch(IOException e) {
throw new RuntimeException("Can't fetch file content from url", e);
}
}
protected void onPostExecute(String r) {
Toast.makeText(getApplicationContext(), "String from file is: " + r,
Toast.LENGTH_LONG).show();
}
};
task.execute();
This question already has answers here:
Android "Only the original thread that created a view hierarchy can touch its views."
(33 answers)
Closed 5 years ago.
I've got this simple timer in my app which is runs in every 3 seconds.
It works perfectly if it's not in a fragment class.
But here in fragment I always got the error: Only the original thread that created a view hierarchy can touch its views.
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
String timeStamp = new SimpleDateFormat(
"yyyy.MM.dd HH:mm:ss").format(Calendar
.getInstance().getTime());
System.out.println("TimeStamp: " + timeStamp);
// Read And Write Register Sample
port = Integer.parseInt(gConstants.port);
String refe = "0";// HEX Address
ref = Integer.parseInt(refe, 16);// Hex to int
count = 10; // the number Address to read
SlaveAddr = 1;
astr = gConstants.ip; // Modbus Device
InetAddress addr;
try {
addr = InetAddress.getByName(astr);
con = new TCPMasterConnection(addr); // the
// connection
} catch (UnknownHostException e2) {
e2.printStackTrace();
}
// 1.Prepare the request
/************************************/
Rreq = new ReadMultipleRegistersRequest(ref, count);
Rres = new ReadMultipleRegistersResponse();
Rreq.setUnitID(SlaveAddr); // set Slave Address
Rres.setUnitID(SlaveAddr); // set Slave Address
// 2. Open the connection
con.setPort(port);
try {
con.connect();
System.out.println("Kapcsolódva!");
} catch (Exception e1) {
e1.printStackTrace();
}
con.setTimeout(2500);
// 3. Start Transaction
trans = new ModbusTCPTransaction(con);
trans.setRetries(5);
trans.setReconnecting(true);
trans.setRequest(Rreq);
try {
trans.execute();
} catch (ModbusIOException e) {
e.printStackTrace();
} catch (ModbusSlaveException e) {
e.printStackTrace();
} catch (ModbusException e) {
e.printStackTrace();
}
/* Print Response */
Rres = (ReadMultipleRegistersResponse) trans
.getResponse();
System.out.println("Connected to= " + astr
+ con.isConnected() + " / Start Register "
+ Integer.toHexString(ref));
count = 10;
for (int k = 0; k < count; k++) {
System.out.println("The value READ: "
+ Rres.getRegisterValue(k) + " "
+ Rres.getUnitID());
ki_adat = ki_adat + Rres.getRegisterValue(k) + "\n";
// Adatbázisba írás
ContentValues modbusData = new ContentValues();
modbusData.put("Value", Rres.getRegisterValue(k)); // tábla
// +
// érték
modbusData.put("timeStamp", timeStamp);
try {
gConstants.db.beginTransaction();
gConstants.db
.insert("Modbus", null, modbusData);
gConstants.db.setTransactionSuccessful();
} finally {
gConstants.db.endTransaction();
}
}
kiir.setText(ki_adat);
ki_adat = "";
}//run vége
}, 0, 3000);
This error occurs when trying to access UI elements from any thread that is not the UI thread.
To access/modify elements from a non-UI-thread, use runOnUIThread.
However as you need to change a UI element from within a fragment, runOnUIThread should be invoked onto the fragments owning activity. You can do this through getActivity().runOnUIThread().
EG:
timer.schedule(new TimerTask() {
#Override
public void run() {
// Your logic here...
// When you need to modify a UI element, do so on the UI thread.
// 'getActivity()' is required as this is being ran from a Fragment.
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
// This code will always run on the UI thread, therefore is safe to modify UI elements.
myTextBox.setText("my text");
}
});
}
}, 0, 3000); // End of your timer code.
For further information see the following documentation:
Android Fragments (specifically, getActivity()).
TimerTask.
Invoking a Runnable on the UI thread.
you need to use the runOnUIThread() function I have an example somwhere that I will post when I find it.
you need to give your timer an instance of MainActivity alternatively see this question I asked Android image timing issues with what sounds like a similar thing to what you were trying to do
public static void updateText(Activity act, resID)
{
loadingText = (TextView) activity.findViewById(R.id.loadingScreenTextView);
act.runOnUiThread(new Runnable()
{
public void run()
{
loadingText.setText(resID);
}
});
}
You are doing UI operation from another thread. I suggest you to use following.
runOnUiThread(new Runnable() {
#Override
public void run() {
kiir.setText(ki_adat);
}
2 solutions :
Use the View.post(Runnable) method
Use the Activity.post(Runnable) method
And put the myTextView.setText(str) call in the run() method of the Runnable object.
Try this:
textView.post(new Runnable() {
#Override
public void run() {
textView.setText("Hello!"); }
});
TRY THIS: put this part of code somewhere but not in activity onCreate method
public void LoadTable(final String u, final String k)
{
// runOnUiThread need to be used or error will appear
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
//method which was problematic and was casing a problem
createTable(u, k);
}
});
} catch (Exception exception) {
createAndShowDialog(exception, "Error");
}
return null;
}
}.execute();
}
Try this
new CountDownTimer(365*24*60*60, 3000) {
public void onTick(long millisUntilFinished) {
String timeStamp = new SimpleDateFormat(
"yyyy.MM.dd HH:mm:ss").format(Calendar
.getInstance().getTime());
System.out.println("TimeStamp: " + timeStamp);
// Read And Write Register Sample
port = Integer.parseInt(gConstants.port);
String refe = "0";// HEX Address
ref = Integer.parseInt(refe, 16);// Hex to int
count = 10; // the number Address to read
SlaveAddr = 1;
astr = gConstants.ip; // Modbus Device
InetAddress addr;
try {
addr = InetAddress.getByName(astr);
con = new TCPMasterConnection(addr); // the
// connection
} catch (UnknownHostException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
// 1.Prepare the request
/************************************/
Rreq = new ReadMultipleRegistersRequest(ref, count);
Rres = new ReadMultipleRegistersResponse();
Rreq.setUnitID(SlaveAddr); // set Slave Address
Rres.setUnitID(SlaveAddr); // set Slave Address
// 2. Open the connection
con.setPort(port);
try {
con.connect();
System.out.println("Kapcsolódva!");
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
con.setTimeout(2500);
// 3. Start Transaction
trans = new ModbusTCPTransaction(con);
trans.setRetries(5);
trans.setReconnecting(true);
trans.setRequest(Rreq);
try {
trans.execute();
} catch (ModbusIOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ModbusSlaveException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ModbusException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/* Print Response */
Rres = (ReadMultipleRegistersResponse) trans
.getResponse();
System.out.println("Connected to= " + astr
+ con.isConnected() + " / Start Register "
+ Integer.toHexString(ref));
count = 10;
for (int k = 0; k < count; k++) {
System.out.println("The value READ: "
+ Rres.getRegisterValue(k) + " "
+ Rres.getUnitID());
ki_adat = ki_adat + Rres.getRegisterValue(k) + "\n";
// Adatbázisba írás
ContentValues modbusData = new ContentValues();
modbusData.put("Value", Rres.getRegisterValue(k)); // tábla
// +
// érték
modbusData.put("timeStamp", timeStamp);
try {
gConstants.db.beginTransaction();
gConstants.db
.insert("Modbus", null, modbusData);
gConstants.db.setTransactionSuccessful();
} finally {
gConstants.db.endTransaction();
}
}
kiir.setText(ki_adat);
ki_adat = "";
}
public void onFinish() {}
}.start();