I have a TextView with the id android:id="#+id/yazi", and I have a button that has build in android:OnClick="gonderB"
and I can complie this code:
package com.seri.bir;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
Bilmez b;
TextView t;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b = new Bilmez();
t = (TextView) findViewById(R.id.yazi);
}
public void gonderB (View v,TextView t,Bilmez b){
String s = " ..."+this;
b.yaziYaz(v,s,t);
}
}
class Bilmez {
public void yaziYaz(View v,String s,TextView t){
t.setText(s);
}
}
However I have an error.
Can I setText in another class?
You can overwrite onClick of the activity. Avoid the using of the android:OnClick="gonderB" line in the xml file. I think it is better to implement the onClickListener and attach it to View Objects within your code.
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
Bilmez b;
TextView t;
Button bt;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b = new Bilmez();
t = (TextView) findViewById(R.id.yazi);
Button bt = (Button) findViewById(R.id.btn);
bt.setOnClickListener(this);
}
#Override
public void onClick(View clickedView) {
switch (clickedView.getId()) {
case R.id.btn:
String s = "...." + this;
b.changeText(t,s);
break;
}} //end of main class }
In the changeText method you change the text of the TextView. This method can if be placed in another class if you like that.
class Bilmez {
public void changeText(TextView t, String s){
t.setText(s);
}
}
Perhaps what you are experiencing is a need to run the function on the UI thread?
public void yaziYaz(View v,final String s,final TextView t) {
runOnUiThread(new Runnable() {
public void run() {
t.setText(s);
}
});
}
i think you should do that:
public void gonderB (new View v,TextView t,Bilmez b){
String s = " ..."+this;
b.yaziYaz(v,s,t);
}
Related
Sorry for my bad English I'm a beginner of android and now I'm stuck.
Now my Question is how can I set the random colors to the background with the OnClickListener. Can you maybe help my with this problem?
I have one class (Kleurenpalet.java)
package com.example.pstek.randomcolor;
import android.graphics.Color;
import java.util.Random;
public class Kleurenpalet{
private static String[] kleur = {
"#39add1", // light blue
"#3079ab", // dark blue
"#3FD52D", // green
"FFFF0000", // red
""};
public int getRandomColor() {
Random rand = new Random();
int color = rand.nextInt(kleur.length);
return Color.parseColor(kleur[color]);
}
}
And I have my main class :
package com.example.pstek.tegeltjeswijsheid;
import android.support.constraint.ConstraintLayout;
import android.support.constraint.solver.widgets.ConstraintWidget;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Layout;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
private ConstraintLayout layout;
private Button randombutton;
int randomColor = new Kleurenpalet().getRandomColor();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layout = findViewById(R.id.layout);
randombutton = findViewById(R.id.button);
randombutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
layout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), ;
}
});
}
}
in the MainActivity code this :
public class MainActivity extends AppCompatActivity {
private ConstraintLayout layout;
private Button randombutton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layout = findViewById(R.id.layout);
randombutton = findViewById(R.id.button);
randombutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int randomColor = new Kleurenpalet().getRandomColor();
layout.setBackgroundColor(randomColor);
}
});
}
}
Perhaps call setBackgroundColor with the initialized color:
layout.setBackgroundColor(randomColor);
Or a different one each time:
layout.setBackgroundColor(new Kleurenpalet().getRandomColor());
I do not understand what you try to do here:
layout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), ;
Why did you leave empty space there? Moreover, if you parse color in your Kleurenpalet, you must use without ContextCompat. Just set your color like this:
layout.setBackgroundColor(randomColor);
ContextCompat is for parsing color from resources file, for instance:
layout.setBackgroundColor(
ContextCompat.getColor(
getApplicationContext(),
R.color.colorPrimary
)
);
You must put "Random Num" and "layout set Color" in button click event :
randombutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int randomColor = new Kleurenpalet().getRandomColor();
layout.setBackgroundColor(randomColor);
}
});
I created a ListDialog extending a DialogFragment class and I have a problem with understanding of this code in the DijalogX class
((MainActivity)getActivity()).setTextField(selectedItem);
I understand that with this code above I put selected String variable to the setTextField method as an argument and after that this variable is showed in TextView on MainActivity class.
My questions:
Why I need a cast from getActivity() to the MainActivity and how I get access from DijalogX(fragment) to the method setTextField in MainActivity? Please explain a little about this process.
I also tried instead of ((MainActivity)getActivity()).setTextField(selectedItem)
use an Interface and everything works nice and I got the same resoult but I am wondering what is better solution here Interface or ((MainActivity)getActivity()).setTextField(selectedItem)?
MainActivity
package com.example.dezox.dijaloglist;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity{
private Button btnStartDialog;
private TextView tvSelectedOption;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initWidgets();
setupListener();
}
private void initWidgets() {
btnStartDialog = findViewById(R.id.btnDialog);
tvSelectedOption = findViewById(R.id.tvselectedOption);
}
private void setupListener() {
btnStartDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DijalogX dijalogX = new DijalogX();
dijalogX.show(getSupportFragmentManager(), "dx");
tvSelectedOption.setText("");
}
});
}
public void setTextField(String odabrano){
tvSelectedOption.setText(odabrano);
}
public String getTextField(){
return tvSelectedOption.getText().toString();
}
}
DijalogX
package com.example.dezox.dijaloglist;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
public class DijalogX extends DialogFragment {
private String[] languageList;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initListResource();
}
private void initListResource() {
languageList = getResources().getStringArray(R.array.language_list);
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(),
android.R.style.Theme_Material_Dialog_Alert)
.setTitle("Select Language: ")
.setItems(languageList, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String selectedItem = languageList[which];
//THIS PART OF THE CODE I DONT UNDERSTAND:
((MainActivity)getActivity()).setTextField(selectedItem);
}
});
return builder.create();
}
}
You have declared a method in MainActivity called setTextField. If you called
Activity a = getActivity();
you would not be able to call your custom method (it is on your derived class, not the base Activity class).
a.setTextField(selectedIte); // WON'T WORK - NO SUCH METHOD
If instead you call
MainActivity ma = (MainActivity)getActivity();
it is now cast as your derived class and you can then call
ma.setTextField(selectedItem);
Doing it in two lines like this is the same as calling the one-liner in your code
((MainActivity)getActivity()).setTextField(selectedItem);
As far as casting vs. an interface, an interface is a bit more flexible of an approach. If you tried to use this fragment in a different activity (not MainActivity) the casting approach would fail. If you are only ever going to use the fragment in this Activity then either would work.
I try to develop a simple Android App with one Button which generates new TextViews on each click.
import android.app.Activity;
import android.os.Bundle;
import android.text.Layout;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class CreateTV extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button mCreate = (Button)findViewById(R.id.btnCreate);
mCreate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
((Button) v).setText("Clicked");
TextView mTV1 = new TextView(this);
}
});
}
}
My code is wrong because of:
TextView mTV1 = new TextView(this);
I could find some similar examples, which generate objects programmatically in onCreate(). But I want to generate and modify new objects in onClick().
Would anybody please help?
Change
TextView mTV1 = new TextView(this);
to
TextView mTV1 = new TextView(CreateTV.this);
Views can only be instantiated with a context as parameter
As you can see in the documentation a TextView needs the context to be created. TextView(Context context)
Since you are trying to create a TextView inside a ClickListener you can not use this as a reference to a Context-extending object.
As McAdam331 pointed out, use new TextView(getActivity), this works because Activity extends Context.
In addition to change TextView mTV1 = new TextView(this); to TextView mTV1 = new TextView(CreateTV.this);, you must add the TextView within a view like the following:
import android.app.Activity;
import android.os.Bundle;
import android.text.Layout;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class CreateTV extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button mCreate = (Button)findViewById(R.id.btnCreate);
mCreate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
((Button) v).setText("Clicked");
TextView mTV1 = new TextView(CreateTV.this);
addContentView(mTV1);
}
});
}
}
I would prefer adding a Context, setting it to final and then call the Textview using the Context.
Example:
public class CreateTV extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button mCreate = (Button)findViewById(R.id.btnCreate);
final Context mContext = this;
mCreate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
((Button) v).setText("Clicked");
TextView mTV1 = new TextView(mContext);
addContentView(mTV1);
}
});
}
}
If you want to use the Context outside the onCreate method (and within Listeners) you can define a Context.
private Context context;
public void onCreate(....) {
this.context = this;
}
private void aMethod() {
context....
}
Theres another way doing such cool stuff. Create a Class and extends it by Application.
public class MainApplication extends Application {
public static Context getContext() { return this; }
}
Then add the MainApplication to your Manifest.
<application
android:name=".MainApplication"
>
and access it from everywhere with MainApplication.getContext();
Good day. I'm having some issues with my android project specifically listview. I tried searching for other information here in this site, and implemented some of the answers. However, it is still not working.
The error specifically is
NullPointerException at line 76 at MainActivity
Here is the code of my MainActivity
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class MainActivity extends Activity {
final ArrayList<String> studentName = new ArrayList<String>();
ArrayAdapter<String> aa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView myList = (ListView) findViewById(R.id.listName);
aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, studentName);
myList.setAdapter(aa);
//droid.R.id.list;
//add
Button bAdd = (Button) findViewById(R.id.addstudent);
bAdd.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
startActivity(new Intent("android.intent.action.ADDSTUDENTS"));
}
});
//edit
Button bEdit = (Button) findViewById(R.id.editstudent);
bEdit.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View x) {
startActivity(new Intent("android.intent.action.EDITSTUDENTS"));
}
});
//edit
Button bDelete = (Button) findViewById(R.id.deletestudent);
bDelete.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View x) {
startActivity(new Intent("android.intent.action.DELETESTUDENTS"));
}
});
}
public ArrayList<String> getArray(){
return studentName;
}
public void notifyArray(){
aa.notifyDataSetChanged();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
and line 76 by the way is
aa.notifyDataSetChanged();
Here is my code for the AddStudents class
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class AddStudents extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.add_student);
Button bAddStudents = (Button) findViewById(R.id.add);
final EditText et = (EditText) findViewById(R.id.student_name);
bAddStudents.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
MainActivity as = new MainActivity();
as.getArray().add(et.getText().toString());
as.notifyArray();
finish();
}
});
Button bBack = (Button) findViewById(R.id.backadd);
bBack.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
finish();
}
});
}
}
and the xml part with the list view is
<ListView
android:id="#+id/listName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" >
</ListView>
I hope you can help me cause I want to also learn what my mistakes are. I can add other information if you want.
In your AddStudents class, you're calling notifyArray() right after you instantiated MainActivity. MainActivity.onCreate() will not be called just by instantiating it.
Instantiating your MainActivity there is probably not what you want anyway (because that object will be disposed directly after the onClick handler is done).
What you want instead is to access the existing instance of MainActivity. For that, add a reference to the current instance to a static member of your MainActivity class, e.g.
public class MainActivity extends Activity {
public static MainActivity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
activity = this;
}
}
Then in your AddStudent class access it via
MainActivity.activity.notifyArray()
This is not the most beautiful way to solve your issue, but it works as long as you can be sure to only have one MainActivity instance. (If not, you could make the array itself static; or create a Singleton wrapper class for it.)
notifyArray() is being called before onCreate.
Try calling getArray().add(et.getText().toString()); and notifyArray(); inside onResume() of MainActivity and NOT from AddStudentActivity( not recommended!)
So onResume() you would ideally want to add a new student to the list, so in your case, you can retrieve the student name using a common sharable object like a hashtable or somethiing similar, make it a singleton, and use it from anywhere in the applciation
The common class may go something like:
class CommonHashtable{
private static Hashtable<String, Object> commonHashtable = null;
public static getInstance(){
if(commonHashtable == null)
commonHashtable = new Hashtable<String, Object>();
return commonHashtable;
}
on getInstance(), it returns a commonHashtable which can be used to store values temporarily!
so, add this on addbutton click event
Hashtable hash = CommonHashtable.getInstance();
hash.put("NEW_STUDENT_NAME", et.getText().toString());
and add this in you onResume() of MainActivity
Hashtable hash = CommonHashtable.getInstance();
Object studentName = (String) hash.get("NEW_STUDENT_NAME");
if(studentName != null){
notifyArray();
}
I have 3 button and 3 textview.When i press first button i want to see 10 sec later which is writing in the first textview.i press second button i want to see someting 5 sec later which is writing in the second textview .i press third button,i want to see textview which is writing immediately.
My question how can i work all multithread in the view without lock other view? I tried ASCYNTask but it doestn work.
Can anybody give me any suggestion?
My Activity:
package com.example;
import android.app.Activity;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MyActivity extends Activity
{
Button a,b,c;
TextView ta,tb,tc;
Ascyn ascyn,ascyn2,ascyn3;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
a=(Button)findViewById(R.id.ba);
b=(Button)findViewById(R.id.bb);
c=(Button)findViewById(R.id.bc);
ta=(TextView)findViewById(R.id.ta);
tb=(TextView)findViewById(R.id.tb);
tc=(TextView)findViewById(R.id.tc);
ascyn=new Ascyn(this);
ascyn2=new Ascyn(this);
ascyn3=new Ascyn(this);
a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ascyn.execute();
SystemClock.sleep(5000);
ta.setText("ok");
}
});
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ascyn2.execute();
SystemClock.sleep(1000);
tb.setText("ozaman");
}
});
c.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ascyn3.execute();
tc.setText("byby");}
});
}
}
Ascyn:
package com.example;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
/**
* Created by IntelliJ IDEA.
* User: duygukahraman
* Date: 20.02.2012
* Time: 15:44
* To change this template use File | Settings | File Templates.
*/
public class Ascyn extends AsyncTask<Void,String,Void> {
private Context ctx;
ProgressDialog dialog;
public Ascyn(Context context){
ctx=context;
dialog=new ProgressDialog(ctx);
}
#Override
protected void onPreExecute() {
// dialog.setTitle("Please wait");
// dialog.show();
}
#Override
protected Void doInBackground(Void... unused) {
// SystemClock.sleep(20000);
return (null);
}
#Override
protected void onPostExecute(Void unused) {
dialog.dismiss();
}
}
You have to create separate Async class for each thread like.
public class AscynThread1 extends AsyncTask<Void,String,Void> { // }
public class AscynThread2 extends AsyncTask<Void,String,Void> { // }
public class AscynThread3 extends AsyncTask<Void,String,Void> { // }
You don't need threads, if you simply want to write some text in a textview. Use a handler instead.
Handler handler = new Handler();
public void method() {
handler.postDelayed(new Runnable() {
public void run() {
textView.setText("Your text");
}
}, 5000);
}