Android: Constantly updating TextView with a new value - java

I need some suggestions as to how I can update a Textview located in the XML with a value generated through my code.
The program draws a straight line through the canvas, I want the textView to reflect the line's tip x-value.
My code as follows:
package com.example.threadexperiment1;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
lineDrawing InfiniteLine;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
InfiniteLine = new lineDrawing (this);
setContentView(R.layout.activity_main);
Thread thread = new Thread(InfiniteLine);
thread.start();
RelativeLayout RL1 = (RelativeLayout)findViewById(R.id.RelativeLayout1);
RL1.addView(InfiniteLine);
}
public class lineDrawing extends View implements Runnable {
float x=100, y=100;
Paint lineColour = new Paint ();
TextView TV1 = (TextView)findViewById(R.id.textView1);
//Constructor
public lineDrawing(Context context) {
super(context);
lineColour.setColor(Color.BLACK);
}
//ondraw codes
#Override
public void onDraw (Canvas canvas){
canvas.drawLine(0,0,x,y,lineColour);
if (x==500){
x=0;
y=0;
}
invalidate();
}
#Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
Thread.sleep(250);
}
catch (Exception e) {}
x+=10;
y+=10;
}
}
}
}

Try textView.setText(string) within the thread.

Related

Canvas not drawing text?

I want to display some text on Screen when the user clicks a button with canvas in android studio. I have been looking at many posts and videos of how to do that. The problem, when I tried their code, when I clicked my button, nothing showed up. Anyone know what I am doing wrong?
Here is my Java class:
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button drawCanvas = findViewById(R.id.draw_canvas_button);
drawCanvas.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Paint paint = new Paint();
Canvas canvas = new Canvas();
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.FILL);
paint.setTextSize(20f);
canvas.drawText("My Text", 10f, 15f, paint);
}
});
}
}
It seems that you have to use a method called onDraw by importing View.
import android.view.View;
public class myClass extends View{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onDraw(Canvas canvas){
super.onDraw(canvas);
//Where you put the code
}

How to set image resource in Android?

I am writing code for a poker game on eclipse and I am stuck on how to make the card clicked in the cardHand area show up in the playedCards area and have it removed from the deck I am drawing it from. Here's the code:
package com.viktorengineering.poker254;
import java.util.Random;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import java.util.Random;
public class Poker extends Activity {
private ImageView mViewDeck;
private ImageView mViewHand;
private ImageView mViewPlayedCards;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.getWindow().setBackgroundDrawableResource(R.drawable.green_back);
mViewDeck = (ImageView) findViewById(R.id.deckImage);
mViewDeck.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int[] imagesArray = {R.drawable.clubs_ace, R.drawable.hearts_seven, R.drawable.diamonds_five,
R.drawable.clubs_three, R.drawable.hearts_eight, R.drawable.spades_six};
Random random = new Random();
mViewHand.setImageResource(imagesArray[new Random().nextInt(6)]);
}
});
mViewHand = (ImageView) findViewById(R.id.cardHand);
mViewHand.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mViewPlayedCards.setImageResource(0);
mViewHand.setImageResource(0);
}
});
mViewPlayedCards = (ImageView) findViewById(R.id.playedCards);
}
}
Your Image in Drawable Folder means use bellow code
mViewPlayedCards.setImageResource(R.drawable.icon);
mViewHand.setImageResource(R.drawable.icon_home);

Why MainActivity cannot be resolved or is not a field?

I have a small project where I need to play with the Battery of an Android device. At first, I wanted to be able to print the Battery so I used this tutorial.
Then, I have created a new Android project called "Testing" in Eclipse, and in MainActivity.java I put this code :
package com.example.testing;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;
import android.R.*;
public class MainActivity extends Activity {
TextView mTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.MainActivity); //This is the MainActivity that contains the error
mTextView = (TextView) findViewById(R.id.batterTest);
findViewById(R.id.getBattery).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mTextView.setText(String.valueOf(batteryLevel));
}
});
new Thread(new ThreadM()).start();
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mArrow);
}
BatteryReceiver mArrow;
private class ThreadM implements Runnable {
#Override
public void run() {
mArrow = new BatteryReceiver();
IntentFilter mIntentFilter = new IntentFilter();
mIntentFilter.addAction(Intent.ACTION_BATTERY_LOW);
mIntentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
mIntentFilter.addAction(Intent.ACTION_BATTERY_OKAY);
Intent batteryIntent = registerReceiver(mArrow, mIntentFilter);
batteryLevel = getBatteryLevel(batteryIntent);
Log.e("Battery Level", String.valueOf(batteryLevel));
}
}
float batteryLevel;
private class BatteryReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
if (arg1.getAction().equalsIgnoreCase(Intent.ACTION_BATTERY_LOW) || arg1.getAction().equalsIgnoreCase(Intent.ACTION_BATTERY_CHANGED) || arg1.getAction().equalsIgnoreCase(Intent.ACTION_BATTERY_OKAY)) {
int level = arg1.getIntExtra("level", 0);
Toast.makeText(MainActivity.this,"Current Battery " + level + " %", Toast.LENGTH_LONG).show();
mTextView.setText(String.valueOf("Battery Level Change Detect through Receiver = " + level));
}
}
}
public float getBatteryLevel(Intent batteryIntent) {
int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
if (level == -1 || scale == -1) {
return 50.0f;
}
return ((float) level / (float) scale) * 100.0f;
}
}
Actually this should just run a simple activity with the Battery level printed on the screen. But it does not because of one error. "MainActivity cannot be resolved or is not a field" (see the commented line).
Do you have any idea why ? I would like to have this code working so I can go on then.
Thank you.
You need to change
setContentView(R.layout.MainActivity);
to
setContentView(R.layout.activity_main);
assuming you have a layout called activity_main.xml and not MainActivity which is actually the name of your Activity class
and Remove
import android.R.*;
and import
import com.example.testing.R;

Got irritating error with getLoaderManager.initLoader

I'm trying to use loader with asynctaskloader to load my listview on a fragment but got error with starting the loader:
The method initLoader(int, Bundle, LoaderManager.LoaderCallbacks) in the type LoaderManager is not applicable for the arguments (int, null, context)
I know many have encounterd this error and i did researched but still not solved, can't understand why. If anyone got any ideas please answwer and thanks in advance!
here's my code:
import java.util.ArrayList;
import com.bblackbb.jotdownv2.R;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.content.AsyncTaskLoader;
import android.content.Loader;
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.view.View.OnClickListener;
import android.app.Activity;
public class WhiteNote extends Fragment implements **strong text**LoaderManager.LoaderCallbacks<ArrayList<NoteItems>> {
private NoteDatabase note_database;
private int i=0;
public Context context;
public NoteListAdapter noteListAdapter;
public ListView note_listview_container;
public SQLiteDatabase note_sqldb;
public Cursor c;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.white_note, container, false);
context=getActivity();
note_database = new NoteDatabase(context);
final EditText text_ed_1;
final EditText text_ed_2;
Button button_addNote;
Button button_listallNote;
Button button_delallNote;
text_ed_1 = (EditText)rootView.findViewById(R.id.textedit1);
text_ed_2 = (EditText)rootView.findViewById(R.id.textedit2);
button_addNote = (Button)rootView.findViewById(R.id.button1);
button_listallNote = (Button)rootView.findViewById(R.id.button2);
button_delallNote = (Button)rootView.findViewById(R.id.button3);
button_addNote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
note_database.open();
note_database.createData(text_ed_1.getText().toString(),text_ed_2.getText().toString());
//i++;
note_database.close();
}
});
button_listallNote.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
note_database.open();
note_database.get_NoteListAdapter();
note_listview_container.setAdapter(note_database.noteListAdapter);
getLoaderManager().initLoader(0, null,context);
note_database.close();
}
});
button_delallNote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
note_database.open();
note_database.deleteAllNote();
note_database.close();
}
});
return rootView;
}
#Override
public Loader<ArrayList<NoteItems>> onCreateLoader(int id, Bundle args) {
return new NoteItemsLoader(context, note_database);
}
#Override
public void onLoadFinished(Loader<ArrayList<NoteItems>> loader,
ArrayList<NoteItems> data) {
note_listview_container.setAdapter(new NoteListAdapter(context,data));
}
#Override
public void onLoaderReset(Loader<ArrayList<NoteItems>> loader) {
note_listview_container.setAdapter(null);
}
}
class NoteItemsLoader extends AsyncTaskLoader<ArrayList<NoteItems>> {
private ArrayList<NoteItems> loader_note_items= new ArrayList<NoteItems>();
private NoteDatabase loader_db;
public NoteItemsLoader(Context context, NoteDatabase db) {
super(context);
loader_db = db;
}
#Override
protected void onStartLoading() {
if (loader_note_items != null) {
deliverResult(loader_note_items); // Use the cache
}
else
forceLoad();
}
#Override
protected void onStopLoading() {
cancelLoad();
}
#Override
public ArrayList<NoteItems> loadInBackground() {
loader_db.open(); // Query the database
ArrayList<NoteItems> note_items = new ArrayList<NoteItems>();
loader_db.get_NoteListLoader(note_items,loader_db);
loader_db.close();
return note_items;
}
#Override
public void deliverResult(ArrayList<NoteItems> data) {
loader_note_items = data; // Caching
super.deliverResult(data);
}
#Override
protected void onReset() {
super.onReset();
onStopLoading();
loader_note_items = null;
}
#Override
public void onCanceled(ArrayList<NoteItems> data) {
super.onCanceled(data);
loader_note_items = null;
}
protected void onReleaseResources(ArrayList<NoteItems> data) {}
}
replace
getLoaderManager().initLoader(0, null,context);
with
getLoaderManager().initLoader(0, null,WhiteNote.this);
here your WhiteNode class implements LoaderManager.LoaderCallbacks but your Activity class in not implementing. so you have to pass reference of WhiteNote class.
and once check imports section as #Praveen Sharma said
Try to replace your old imports with these
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
hope this will fix your problem.

How to draw to canvas on onResume

I have an android app that draws to a canvas. Up to now I've been drawing each time I create the app usine onCreate as such:
package com.example.drawdemo;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
public class DrawDemo extends Activity {
DrawView drawView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
drawView = new DrawView(this);
drawView.setBackgroundColor(Color.WHITE);
setContentView(drawView);
}
}
However I'd like to migrate the drawing to onResume. Ideally I do not draw the first time someone starts the program, only when they resume the program. Why do the following two code snippets not work:?
package com.example.drawdemo;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
public class DrawDemo extends Activity {
DrawView drawView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
drawView = new DrawView(this);
drawView.setBackgroundColor(Color.WHITE);
setContentView(drawView);
}
#Override
public void onResume(){
drawView = new DrawView(this);
drawView.setBackgroundColor(Color.WHITE);
setContentView(drawView);
}
}
and
package com.example.drawdemo;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
public class DrawDemo extends Activity {
DrawView drawView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onResume(){
drawView = new DrawView(this);
drawView.setBackgroundColor(Color.WHITE);
setContentView(drawView);
}
}
Make sure you call super.onResume() - your activity will not function properly without it.

Categories