Hi, why this code working "onCreate" but don`t working in the button
Realy I use not more then 20Mb, but for testing I inserted 90Mb
public class MainActivity extends AppCompatActivity {
TextView textView; DataInputStream textFileStream = null;
public void readbigtext(){
try {
textFileStream = new DataInputStream(getAssets().open(String.format("test1.txt")));
} catch (IOException e) {e.printStackTrace();}
Scanner sc = new Scanner(textFileStream);
while (sc.hasNextLine()) {textView.append(sc.nextLine());}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bigbutton = (Button) findViewById(R.id.bigbutton);
textView = (TextView) findViewById(R.id.bigfile);
textView.append("test begin");
//90Mb here IS WORKING!
// readbigtext();
bigbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//90Mb here DON`T WORKING
readbigtext();
}
});
}
}
Related
very noob in programming here, i have an activity (control) in android studio and a class (MesageSender) which extends AsyncTask ,
so i wanted to give a text in activity control via edittext and save that to a string in class messagesender and display it back to control in a textview , here is the code for my control (activity) and MessageSender (class)
below is code of control activity
public class controler extends AppCompatActivity {
public MessageSender mmessagesender = new MessageSender();
static EditText et;
Button bt;
static TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
setContentView(R.layout.activity_controler);
et= findViewById(R.id.editText);
bt = findViewById(R.id.button);
tv = findViewById(R.id.tv);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mmessagesender.ip = et.getText().toString();
}
});
}
}
Here ip is string from MessageSender class and et is edittext in controll activity
Below is code of MessageSender class
public class MessageSender extends AsyncTask<String,Void,Void> {
Socket s;
DataOutputStream dos;
PrintWriter pw;
String ip;
#Override
protected Void doInBackground(String... Voids) {
String message = Voids[0];
try{
s =new Socket(ip,123);
if(ip != null){
controler.tv.setText(ip);
}
else{
controler.tv.setText("no ip");
}
}
catch(IOException e) {
e.printStackTrace();
}
return null;
}
}
the problem was i cannot see the textview tv in control change to what i gave in edittext et
any help is appreciated , thanks :)
I am new to Android development. I have an app in which the user creates multiple names (as if they were players of a game). These "players" appear as a matrix is used in the same activity. (Being possible here to exclude any player).
I want to display all of these players (MainActivity) in another activity (Main2Activity), showing only the first player added and, clicking a button, switch to the second player.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
RecyclerView recyclerView;
TextView textAdd;
EditText etAdd;
ArrayList<Model> models = new ArrayList<Model>();
MyAdapter myAdapter;
int position;
Button prox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prox = findViewById(R.id.prox);
prox.setOnClickListener(new View.OnClickListener() {
//next screen
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
String nome = etAdd.getText().toString();
intent.putExtra("value", nome);
startActivity(intent);
}
});
recyclerView = findViewById(R.id.recyclerView);
textAdd = findViewById(R.id.text_adicionar);
etAdd = findViewById(R.id.et_Adicionar);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
myAdapter = new MyAdapter(getApplicationContext(),
models, new MyAdapter.Onclick() {
#Override
public void onEvent(Model model, int pos) {
position = pos;
etAdd.setText(model.getId());
}
});
recyclerView.setAdapter(myAdapter);
textAdd.setOnClickListener(this);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.text_adicionar: {
insertItem(String.valueOf(etAdd.getText()));
}
break;
}
}
private void insertItem(String name) {
Gson gson = new Gson();
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", name);
Model model = gson.fromJson(String.valueOf(jsonObject), Model.class);
models.add(model);
myAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public class Main2Activity extends AppCompatActivity implements View.OnClickListener {
Button play;
TextView text_player_name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
play = findViewById(R.id.play);
text_player_name = findViewById(R.id.text);
play.setOnClickListener(this);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.play: {
String name = getIntent().getExtras().getString("value");
text_player_name.setText(String.valueOf(name));
}
break;
}
}
}
I'm not sure if I fully understand your question, but are you just looking for a way to pass data from one Activity to another?
If so, use .putExtra() with your Intent for starting the next Activity.
In the onCreate method for your second Activity, use .getExtras() to retrieve the data.
In 1st Activity
Intent intent = new Intent(this, Activity2.class);
intent.putExtra("DataName", data);
startActivity(intent);
In the 2nd Activity
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
String[] dataArray = getIntent().getExtras().get("DataName"));
}
EDIT:
public class Main2Activity extends AppCompatActivity implements View.OnClickListener {
Button play;
TextView text_player_name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
play = findViewById(R.id.play);
text_player_name = findViewById(R.id.text);
play.setOnClickListener(this);
}
#Override
public void onClick(View v) {
String name = getIntent().getExtras().getString("value");
text_player_name.setText(String.valueOf(name));
}
I'm trying to get input stream from URL to be displayed on TextView when clicked on a certain button in my android app. I used someone else's code from internet tutorial step by step but it doesn't work for me. The TextView is always empty even though it should already show the text. I would deeply appreciate any help.
public class fetchData extends AsyncTask<Void, Void, Void> {
String data="";
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("https://api.myjson.com/bins/j5f6b");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while(line != null){
line = bufferedReader.readLine();
data = data + line;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
CurrencyConvert.text.setText(this.data);
}
}
public class CurrencyConvert extends AppCompatActivity {
Button click;
public static TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_currency_convert);
click = (Button) findViewById(R.id.button);
text = (TextView) findViewById(R.id.fetchText);
// data.setText("");
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fetchData process = new fetchData();
process.execute();
}
});
}
}
You shouldn't declare TextView as static varible of Activity class. Instead pass activity instance to fetchData class constructor (btw. class names should start with uppercase)
public class FetchData extends AsyncTask<Void, Void, Void> {
CurrencyConvert activity;
public FetchData(CurrencyConvert activity) {
this.activity= activity;
}
#Override
protected Void doInBackground(Void... arg0) {
// do background stuff...
}
#Override
protected void onPostExecute(Void result) {
activity.setTextInTextView(this.data);
}
In Your Activity declare public method for setting text:
public class CurrencyConvert extends AppCompatActivity {
Button click;
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_currency_convert);
click = (Button) findViewById(R.id.button);
text = (TextView) findViewById(R.id.fetchText);
data.setText("");
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fetchData process = new fetchData(this);
process.execute();
}
});
}
void setTextInTextView(String data) {
text.setText(data);
}
}
I am writing my first android application, and am trying to write an app where you simply click a button to display a message, and can do so as many times as you want. So far I have:
public class MyProject extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView tv = new TextView(this);
Button startButton = (Button) findViewById(R.id.startbutton);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
tv.setText("Hello World!");
setContentView(tv);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {setContentView(R.layout.main);}}, 2000);
}
});
}
}
However doing it this way, when I get back to my main screen and click on the button again...nothing happens. How can I get repeated button clicks to repeat the behaviour?
Your example is very simple and, from what I understand, no multithreading is needed.
You just have to initialize your layout one time, after that you can update the content of the single views.
So... this will set "hello world" string on every button click, you will not notice any difference because the string is always the same :D
public class MyProject extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// this is needed one time only
setContentView(R.layout.main);
// add your textview in xml
final TextView tv = (TextView) findViewById(R.id.textView);
final Button startButton = (Button) findViewById(R.id.startbutton);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
tv.setText("Hello World!");
}
}
}
}
To do something more fun you can set a counter to update on every click, this way the textview change will be noticeable are more fun!!
int i = 0;
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
tv.setText("you have reached " + i);
i++;
}
}
Here, you are calling setContentView to replace the entire current view with a TextView containing "Hello World!" Then after two seconds you setContentView again to set it back to the main layout. Since OnCreate is only called once when the activity is created, the OnClickListener is never set again.
This code will do what you are looking for.
public class MyActivity extends Activity
implements View.OnClickListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
}
private void init() {
setContentView(R.layout.main);
Button startButton = (Button) findViewById(R.id.startbutton);
startButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
TextView tv = new TextView(this);
tv.setText("Hello World!");
setContentView(tv);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
init();
}
}, 2000);
}
}
You may notice that OnClick is a separate method in my example. This is because I implemented the interface View.OnClickListener. I was able to write the implemented method as part of my class and then pass this as an argument to setOnClickListener. I'm explaining this because you mentioned you are new to Java.
TextView txt;
// our handler
Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
//display each item in a single line
txt.setText(txt.getText()+"Item "+System.getProperty("line.separator"));
}
};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txt=(TextView)findViewById(R.id.txt);
}
#Override
protected void onStart() {
super.onStart();
// create a new thread
Thread background=new Thread(new Runnable() {
#Override
public void run() {
for(int i=0;i<10;i++)
{
try {
Thread.sleep(1000);
b.putString("My Key", "My Value: "+String.valueOf(i));
// send message to the handler with the current message handler
handler.sendMessage(handler.obtainMessage());
} catch (Exception e) {
Log.v("Error", e.toString());
}
}
}
});
background.start();
}
}
Note:Handler one type of thread not udpate any UI here
Take an example from here
I am having trouble passing data read from a text file to another class in the app. I can read from the file just fine, but I think I need to use Bundle, but I'm not sure how to do it. I would like to have the second class handle the data from the text file, and then display it in the first class.
Edit: I've figured out how to pass the string from the file using an intent. I'm still working on getting some of the bugs out.
2nd Edit: I know there is a more efficient way of doing this. The only way I can get it to work is to have the first button in MainActivity use startActivity(intent) to allow secondActivity to bundle the string read from the file.
MainActivity.java:
public class MainActivity extends Activity {
Button btn;
Button bReadFile;
TextView tvRead;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.btnNext);
bReadFile = (Button) findViewById(R.id.btnRead);
tvRead = (TextView) findViewById(R.id.tvMain);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//trying to find a way to remove this button
Intent intent = new Intent(MainActivity.this, econdActivity.class);
startActivity(intent);
}
});
bReadFile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String value = getIntent().getExtras().getString("key");
tvRead.setText(value);
}
});
}
}
secondActivity.java:
public class secondActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent mIntent = new Intent(secondActivity.this, MainActivity.class);
mIntent.putExtra("key", readDataFile());
startActivity(mIntent);
}
public String readDataFile() {
String strData = null;
InputStream is = null;
try {
is = getResources().openRawResource(R.raw.data_text);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
strData = br.readLine();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return strData;
}
}
Use the below edited code for your requirement
MainActivity.java
public class MainActivity extends Activity {
Button btn;
Button bReadFile;
TextView tvRead;
String value;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.btnNext);
bReadFile = (Button) findViewById(R.id.btnRead);
tvRead = (TextView) findViewById(R.id.tvMain);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//trying to find a way to remove this button
Intent intent = new Intent(MainActivity.this, secondActivity.class);
startActivityForResults(intent,0);
}
});
bReadFile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
tvRead.setText(value);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
value = data.getStringExtra("key");
}
}
the code for secondActivity.java
public class secondActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent i = new Intent();
i.putExtra("key", readDataFile());
setResult(RESULT_OK, i);
finish();
}
public String readDataFile() {
String strData = null;
InputStream is = null;
try {
is = getResources().openRawResource(R.raw.data_text);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
strData = br.readLine();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return strData;
}
}