[Q] How to update a textView every second. - Android Studio

I have a textview that shows your amount of money and i would like the ui to update every second to visually show how much money you have in real time. Would i be able to accomplish this with a timer?, and if so what would it look like.

Hello,
You should do inside your class, outside of any method:
Code:
TextView tv;
String calculatedString;
MyAsyncTask mAsync = null;
Timer timer = null;
TimerTask task = null;
private class MyAsyncTask extends AsyncTask<String, Void, String> {
public MyAsyncTask(){
}
@Override
protected String doInBackground(String... params) {
//Background operation in a separate thread
//Write here your code to run in the background thread
//calculate here whatever you like
calculatedString = ....;
return null;
}
@Override
protected void onPostExecute(String result) {
//Called on Main UI Thread. Executed after the Background operation, allows you to have access to the UI
tv.setText(calculatedString);
}
@Override
protected void onPreExecute() {
//Called on Main UI Thread. Executed before the Background operation, allows you to have access to the UI
}
}
inside the onCreate after super and setContentView:
Code:
tv = (TextView) findViewById(R.id.tv); //your tv id here
final Handler handler = new Handler();
timer = new Timer();
task = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
MyAsyncTask mAsync = new MyAsyncTask();
mAsync.execute();
}
});
}
};
timer.schedule(task, 0, 1000); //Every 1 second
If you still need help, feel free to ask

I have attached 2 screenshots showing the errors i was given after inputting. Any idea how to fix this?
mmdeveloper10 said:
Hello,
You should do inside your class, outside of any method:
Code:
TextView tv;
String calculatedString;
MyAsyncTask mAsync = null;
Timer timer = null;
TimerTask task = null;
private class MyAsyncTask extends AsyncTask<String, Void, String> {
public MyAsyncTask(){
}
@Override
protected String doInBackground(String... params) {
//Background operation in a separate thread
//Write here your code to run in the background thread
//calculate here whatever you like
calculatedString = ....;
return null;
}
@Override
protected void onPostExecute(String result) {
//Called on Main UI Thread. Executed after the Background operation, allows you to have access to the UI
tv.setText(calculatedString);
}
@Override
protected void onPreExecute() {
//Called on Main UI Thread. Executed before the Background operation, allows you to have access to the UI
}
}
inside the onCreate after super and setContentView:
Code:
tv = (TextView) findViewById(R.id.tv); //your tv id here
final Handler handler = new Handler();
timer = new Timer();
task = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
MyAsyncTask mAsync = new MyAsyncTask();
mAsync.execute();
}
});
}
};
timer.schedule(task, 0, 1000); //Every 1 second
If you still need help, feel free to ask
Click to expand...
Click to collapse

Hello,
For the first image:
You have to import the AsyncTask.
add this
Code:
import android.os.AsyncTask;
with the other imports in your java file.
For your second image:
You haven't wrote the line
Code:
setContentView(R.layout.activity_main);
under your super.onCreate(savedInstanceState); and then the code I said above (I said that on my post )
inside onCreate, where activity_main is your xml layout. And you should have inside that layout, a TextView with an id "tv" (or whatever you like)
and then:
Code:
tv = (TextView) findViewById(R.id.tv); //your tv id here
R.id.tv must much the id you have in your layout. Replace it with the actual id of your TextView. If your id is "tv", write R.id.tv, if it is "mytv" write R.id.mytv. ( I said that on my post also)
Can you show your layout file? (XML - your activity_main.xml). You said that you have a TextView Where is your TextView?

Ok I fixed the problems stated and now only have these two errors remaining
mmdeveloper10 said:
Hello,
For the first image:
You have to import the AsyncTask.
add this
Code:
import android.os.AsyncTask;
with the other imports in your java file.
For your second image:
You haven't wrote the line
Code:
setContentView(R.layout.activity_main);
under your super.onCreate(savedInstanceState); and then the code I said above (I said that on my post )
inside onCreate, where activity_main is your xml layout. And you should have inside that layout, a TextView with an id "tv" (or whatever you like)
and then:
Code:
tv = (TextView) findViewById(R.id.tv); //your tv id here
R.id.tv must much the id you have in your layout. Replace it with the actual id of your TextView. If your id is "tv", write R.id.tv, if it is "mytv" write R.id.mytv. ( I said that on my post also)
Can you show your layout file? (XML - your activity_main.xml). You said that you have a TextView Where is your TextView?
Click to expand...
Click to collapse

Have you imported this?
Code:
import java.util.logging.Handler;
If so, change it to
Code:
import android.os.Handler;

Im not at the computer but I think that should solve my issue I will keep you updated
Sent from my HTC6525LVW using XDA Free mobile app

Hey thanks so much its working perfectly now :good:

Related

I'd like to decrease dialer vibration and I need help with that..

I'm completely noob.
Here are the sources
http://grepcode.com/file/repository...cFeedback.java#HapticFeedback.0mHapticPattern
Code:
public void init(Context context, boolean enabled) {
mEnabled = enabled;
if (enabled)
{
mVibrator = new SystemVibrator(context);
mHapticPattern = new long[] {0, DURATION, 2 * DURATION, 3 * DURATION};
mSystemSettings = new Settings.System();
mContentResolver = context.getContentResolver();
}
}
I need to change mHapticPattern array to adjust vibration duration on dialpad.
So, I can use that
Code:
findAndHookMethod("com.android.phone.common.HapticFeedback", lpparam.classLoader, "init", new XC_MethodHook()
{
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
// BUT I don't know what I have to write here to get it working :(
// I know that this method will be called after init method and I don't know how I can change mHapticPattern array :(
}
});
Or I think I can also change value of Duration
private static final long DURATION = 10;
Click to expand...
Click to collapse
But anyway I do not know how...
I will be glad if anyone will try to help me...
Changing DURATION directly will have no effect. This is because the compiler replaces final static variables with their values (so "10" will be directly used instead of "DURATION").
What you could do is replace the init(Context context, boolean enabled) method entirely. Check out the development tutorial (and other wiki pages) for some hints on where to get started.
GermainZ said:
Changing DURATION directly will have no effect. This is because the compiler replaces final static variables with their values (so "10" will be directly used instead of "DURATION").
What you could do is replace the init(Context context, boolean enabled) method entirely. Check out the development tutorial (and other wiki pages) for some hints on where to get started.
Click to expand...
Click to collapse
Thank you for your answer. But I did not see it till now. That's why my respond is so late.
I had one experience with replacing entire method. But it was just a boolean method. I used this example http://forum.xda-developers.com/showpost.php?p=34609860&postcount=4
And also I've tried to replace whole init method but I have a problem with that string:
Code:
mVibrator = new SystemVibrator(context);
I did
import android.os.SystemVibrator;
but this "android.os.SystemVibrator;" is highlighted with red in eclipse
It says "The import android.os.SystemVibrator cannot be resolved" but the file exists...
I have a code but because of that error I can't test it
S0bes said:
It says "The import android.os.SystemVibrator cannot be resolved" but the file exists...
Click to expand...
Click to collapse
It's possible it's not in the SDK. Use XposedHelpers.findClass(...) to get the SystemVibrator class, then XposedHelpers.newInstance(...) to create a new instance.
@GermainZ please help me. This is the last thing I want to implement. Dialpad vibration is heavy and I think it's not good for vibro inside my phone.
This is what I try but Vibration is gone after that:
PHP:
package com.s0bes.fmspeaker;
import android.content.Context;
import android.os.Vibrator;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XC_MethodReplacement;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import static de.robv.android.xposed.XposedHelpers.findClass;
import static de.robv.android.xposed.XposedHelpers.newInstance;
import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam;
import android.content.ContentResolver;
import android.provider.Settings;
//import android.os.SystemVibrator;
public class bool1 {
static Context context;
private static Vibrator mVibrator ;
private static Settings.System mSystemSettings;
private static ContentResolver mContentResolver;
private static long[] mHapticPattern;
public static void InitResources(final LoadPackageParam lpparam) throws Throwable {
if (lpparam.packageName.equals("com.android.dialer")) {
XposedHelpers.findAndHookMethod("com.android.phone.common.HapticFeedback", lpparam.classLoader,
"init", Context.class, boolean.class, new XC_MethodHook() {
@Override protected void beforeHookedMethod(final MethodHookParam param) throws Throwable {
XposedBridge.log("HOOOKED init" );
//context=(Context) param.args[0];
}
});
XposedHelpers.findAndHookMethod("com.android.phone.common.HapticFeedback", lpparam.classLoader, "init", Context.class, boolean.class, new XC_MethodReplacement() {
@Override
protected Object replaceHookedMethod(MethodHookParam param) throws Throwable {
context=(Context) param.args[0];
XposedBridge.log("REPLACED init. Enabled="+param.args[1] );
Class Myclass = findClass("android.os.SystemVibrator", lpparam.classLoader);
Object mVibrator = newInstance(Myclass, context);
mHapticPattern = new long[] {0, 10, 2 * 10, 8 * 10};
mSystemSettings = new Settings.System();
mContentResolver = context.getContentResolver();
return true;
}
});
}
}
}
EDIT:
Yeehoooo. I got this working
Your post http://forum.xda-developers.com/showpost.php?p=54951841&postcount=8 very helped me.
Instead replace init method I replaced vibrate();
PHP:
XposedHelpers.findAndHookMethod("com.android.phone.common.HapticFeedback", lpparam.classLoader, "vibrate", new XC_MethodReplacement() {
@Override
protected Object replaceHookedMethod(MethodHookParam param) throws Throwable {
Class Myclass = findClass("android.os.SystemVibrator", lpparam.classLoader);
Object mVibrator = newInstance(Myclass, context);
mHapticPattern = new long[] {0, 10, 1 * 10, 1 * 10};
((Vibrator) mVibrator).vibrate(mHapticPattern, -1);
return true;
}
});
}

Badly confused with AsyncTask .. someone please help out .. ty

Am creating a form application which allows users to send a message using http POST request..Am getting a android.os.NetworkOnMainThreadException while running my program. I am fairly new to android dev. Can someone help me by rewriting the network related operation in AsyncTask. If someone can rewrite, i can learn how exactly network tasks can be done using Async. Ty
Code:
public class MainActivity extends Activity {
EditText msgTextField;
Button sendButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//make message text field object
msgTextField = (EditText) findViewById(R.id.msgTextField);
//make button object
sendButton = (Button) findViewById(R.id.sendButton);
}
public void send(View v)
{
//get message from message box
String msg = msgTextField.getText().toString();
//check whether the msg empty or not
if(msg.length()>0) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("localhost");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "01"));
nameValuePairs.add(new BasicNameValuePair("name", msg));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
msgTextField.setText(""); //reset the message text field
Toast.makeText(getBaseContext(),"Successfully Booked!!",Toast.LENGTH_SHORT).show();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
//display message if text field is empty
Toast.makeText(getBaseContext(),"All fields are required",Toast.LENGTH_SHORT).show();
}
}
}
any help ??
Hello,
Make a copy of the send(View v) method and name it sendAsync(View v, EditText msgbox).
Like this:
Code:
public Exception sendAsync(View v, EditText msgbox)
{
[B] HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("localhost");[/B]
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "01"));
nameValuePairs.add(new BasicNameValuePair("name", msgbox.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
return null;
} catch (ClientProtocolException e) {
return e;
} catch (IOException e) {
return e;
}
}
Next, modify the original send(View v) method like this:
Code:
public void send(View v)
{
//get message from message box
String msg = msgTextField.getText().toString();
//check whether the msg empty or not
if(msg.length()>0) {
MyAsyncTask mAsync = new MyAsyncTask(v, getBaseContext(), msgTextField);
mAsync.execute();
} else {
//display message if text field is empty
Toast.makeText(getBaseContext(),"All fields are required",Toast.LENGTH_SHORT).show();
}
}
You can add the below code inside your activity class (outside the onCreate method)
Code:
private class MyAsyncTask extends AsyncTask<String, Void, String> {
View v;
Context context;
EditText msgbox;
Exception e = null;
public MyAsyncTask(View v_, Conext context_, EditText msgbox_){
this.v = v_;
this.context = context_;
this.msgbox = msgbox_;
}
@Override
protected String doInBackground(String... params) {
//Background operation in a separate thread
//Write here your code to run in the background thread
this.e = sendAsync(v, msgbox);
return null;
}
@Override
protected void onPostExecute(String result) {
//Called on Main UI Thread. Executed after the Background operation, allows you to have access to the UI
if(e==null){
//Successful
msgbox.setText(""); //reset the message text field
Toast.makeText(context,"Successfully Booked!!",Toast.LENGTH_SHORT).show();
}
else{
e.printStackTrace();
}
}
@Override
protected void onPreExecute() {
//Called on Main UI Thread. Executed before the Background operation, allows you to have access to the UI
}
@Override
protected void onProgressUpdate(Void... values) {
//Called on Main UI Thread
}
}
However, HttpClient is deprecated for API Level 22 and above, so you should use HttpURLConnection instead. This may help you out for using HttpURLConnection via POST or GET Method.
Now, the doInBackground method, runs in a background thread, automatically created for you, and so we send the data from there, for not crashing the UI (User Interface) of the Android App. If you want, however, to access some UI components, you can do it in the onPostExecute (it is executed after the doInBackground completes) or in the onPreExecute (it is executed before the doInBackground begins). To learn more about the AsyncTask class, check here.
AsyncTask can be used and for other purposes other than sending data over the Internet. In general, you create a class extending the AsyncTask, pass any parameters that you are going to use in the background thread (but not UI components like EditText, you can pass them though, but use them in the onPreExecute or onPostExecute methods, and not in the doInBackground method), and do the stuff you want to run in the background thread inside the doInBackground method. That way, heavy(time consuming) computations or tasks like sending data over the Internet does not make your UI to crash, meaning that the user can press any buttons (for example) without lag or without waiting for the background task to finish.
i tried .. it didnt work for me .. can u give the full code for this please ?
package com.example.formpost;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText msgTextField;
Button sendButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.form);
//make message text field object
msgTextField = (EditText) findViewById(R.id.msgTextField);
//make button object
sendButton = (Button) findViewById(R.id.sendButton);
}
public void send(View v)
{
//get message from message box
String msg = msgTextField.getText().toString();
//check whether the msg empty or not
if(msg.length()>0) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("serverside-script.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "01"));
nameValuePairs.add(new BasicNameValuePair("message", msg));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
msgTextField.setText(""); //reset the message text field
Toast.makeText(getBaseContext(),"Sent",Toast.LENGTH_SHORT).show();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
//display message if text field is empty
Toast.makeText(getBaseContext(),"All fields are required",Toast.LENGTH_SHORT).show();
}
}
}
Click to expand...
Click to collapse
Thanks bro
I just made a correction on the sendAsync method. It should be as follows (I have also updated my initial post):
Code:
public Exception sendAsync(View v, EditText msgbox)
{
[B] HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("localhost");[/B]
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "01"));
nameValuePairs.add(new BasicNameValuePair("name", msgbox.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
return null;
} catch (ClientProtocolException e) {
return e;
} catch (IOException e) {
return e;
}
}
(Replace "localhost" with the actual URL that will handle the POST HTTP request). Also if you are on a local network (LAN), and trying to access the localhost of your PC that is connected to the same LAN as your Android smartphone, then, you should find the local internal IP of your computer, e.g. 192.168.1.1 (you can find that from the command prompt by typing: ipconfig). It's the IPv4 Address on your ethernet or wifi (whatever connection your PC has to the router).
Also make sure that your firewall does not block the connection.
Hope it works. What is the error that you get?
try using volley library for http requests .just a few bunch of line. no need of using async tasks.it will handle it automatically
Sent from my Nexus 4 using Tapatalk
jaison thomas said:
try using volley library for http requests .just a few bunch of line. no need of using async tasks.it will handle it automatically
Sent from my Nexus 4 using Tapatalk
Click to expand...
Click to collapse
Since am new to this whole thing, i wanted to learn with this. It was the only tutorial project i could see. Its been depreciated, but still for learning purpose i wanted to execute it. Still no success.

Trouble with implementing In App Billing into my app...

So I was programming in some In app Billing code for my Android app using Android Studio. I was following an Android tutorial called 'Preparing your In-app Billing Application' at the Android Developer website (not allowed to give a link because I'm a new user). All was going well, until I get to the part where I have to paste their code into my code. Check out their code put into mine (I left the base64EncodedPublicKey empty so nobody would steal it):
Code:
public class MainActivity extends ActionBarActivity {
//Add other java files to the main class
private JokeBook mJokeBook = new JokeBook();
private ColorWheel mColorWheel = new ColorWheel();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Declare View variables
final TextView jokeLabel = (TextView) findViewById(R.id.jokeTextView);
final Button showJokeButton = (Button) findViewById(R.id.showJokeButton);
final RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
final Button moreJokes = (Button) findViewById(R.id.moreJokes);
//On Click
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
String joke = mJokeBook.getJoke();
//Update label with fact
jokeLabel.setText(joke);
int color = mColorWheel.getColor();
relativeLayout.setBackgroundColor(color);
showJokeButton.setTextColor(color);
moreJokes.setTextColor(color);
}
};
showJokeButton.setOnClickListener(listener);
goToTwitter();
goToFacebook();
goToExxellerate();
IabHelper mHelper;
@Override
public void [U]onCreate(Bundle savedInstanceState)[/U] {
// ...
String base64EncodedPublicKey = "";
// compute your public key and store it in base64EncodedPublicKey
[B]mHelper = new IabHelper(this, base64EncodedPublicKey);[/B]
}
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result) {
if (!result.isSuccess()) {
// Oh noes, there was a problem.
[I]Log.d(TAG, "Problem setting up In-app Billing: " + result);[/I]
}
// Hooray, IAB is fully set up!
}
});
@Override
public void [U]onDestroy()[/U] {
super.onDestroy();
if (mHelper != null) mHelper.dispose();
mHelper = null;
}
}
The code that they gave me had many errors when pasted into Android Studio, which were:
TAG has private access in 'android.support.v4.app.FragmentActivity' (Italicized text)
Annotations are not allowed here (@Override)
; expected (Underlined text)
IabHelper (android.view.View.onClickListener, String) in IabHelper cannot be applied to (com.exxellerate.joketeller.MainActivity, String) (Bolded Text)
Any help with fixing there errors? I'm a beginner at code and very confused that the code they gave me was wrong...

New to Forum, New to Android

Hey ladies and gents,
I'm new to your forums, seems it will be a helpful resource as I undertake this new project. I'm not new to programming, but i'm rusty. About 20 years ago I started with Qbasic, in high school i moved on to Visual Studio and C++. But I have been out of it for awhile now.
I started learning a little python to help my dad with his own program. But Decided I wanted to use Android Studio for my own. I have already started looking into tutorials, but have yet to see some information I am looking for. ( Or just don't recognize due to inexperience )
Traditionally, whats best to use for a multiscreen App? I am currently running windows in Fragments. I have a sidescreen that pops out with a menu button (works), windows slide out with options ( works ), when you select the option the window slides away (works) and it brings up the fragment so you can fill in forms (works.)
Inside my Fragments java file I have this
public class ac extends Fragment {
private EditText od_input;
private EditText sp_input;
private EditText hp_input;
private EditText sl_input;
private EditText hl_input;
private EditText return_input;
private EditText vent_input;
private TextView diag_output;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public ac() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment ac.
*/
// TODO: Rename and change types and number of parameters
public static ac newInstance(String param1, String param2) {
ac fragment = new ac();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
EditText odtext;
EditText idtext;
EditText sptext;
EditText hptext;
EditText sltext;
EditText hltext;
EditText returntext;
EditText venttext;
@override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_ac, container, false);
// NOTE : We are calling the onFragmentInteraction() declared in the MainActivity
// ie we are sending "Fragment 1" as title parameter when fragment1 is activated
if (mListener != null) {
mListener.onFragmentInteraction("Air Conditioning");
}
// Here we will can create click listners etc for all the gui elements on the fragment.
// For eg: Button btn1= (Button) view.findViewById(R.id.frag1_btn1);
// btn1.setOnclickListener(...
//odtext = view.findViewById(R.id.odtext);
//idtext = (EditText) findViewById(R.id.idtext);
//sptext = view.findViewById(R.id.sptext);
//hptext = view.findViewById(R.id.hptext);
//sltext = view. findViewById(R.id.sltext);
//hltext = view.findViewById(R.id.hltext);
//returntext = view.findViewById(R.id.returntext);
//venttext = view.findViewById(R.id.venttext);
//TextView diagtext = view.findViewById(R.id.diagtext);
//diagtext.setText((CharSequence) odtext);
return view;
}
@override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// NOTE : We changed the Uri to String.
void onFragmentInteraction(String title);
}
}
Firstly, yes there is a lot of useless crapification going on. Was running different experiments and have not fully cleaned up yet.
But, as people type in the field I want to capture the inputs. Does this require a Listener? Can you capture as they type or do I need a button (Really, Really don't want a button)?
Also, I am unfamiliar with the layout of the java.
Oncreate is when the program boots up?
onCreateview is when the Fragment is booted up?
onattach is when the main activity is associated?
ondetach is when its associated from activity?
I don't fully understand yet where the best place is to add stuff, would it be after onattach?
Thanks for pointing me in the right directions guys.
Chris W.

Using Intent(send mail) in Navigation drawer

I want to send mail from Navigation Drawer using the intent. First, my MainActivity.
Code:
else if(id==R.id.nav_mail) {
fragment = new MailFragment();
}
and MailFragment.
Code:
public class MailFragment extends Fragment {
public MailFragment() {
Intent email = new Intent(Intent.ACTION_SEND);
email.setType("plain/text");
String[] address = {"********@gmail.com"};
email.putExtra(Intent.EXTRA_EMAIL, address);
email.putExtra(Intent.EXTRA_SUBJECT, "Subject___****");
email.putExtra(Intent.EXTRA_TEXT, "Text___****.\n\n");
startActivity(email);
}
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// TextView textView = new TextView(getActivity());
// textView.setText(R.string.hello_blank_fragment);
// return textView;
// }
}
Run to create crash. The reason why I used to use fragment is because I made the simple screen change function fragment.
If you need more code, comment plz.
I didn't get what you are trying to do. If you are trying to invoke the "Select your mail app" screen and then send a message thru the Intent all of this when the user clicks on a row on the drawer then you should just copy the code to
Code:
else if(id==R.id.nav_mail) {
// here
}
without switching any fragment.
By the way, as far as I know, the fragment's public constructor must be empty.
You cannot do it from Fragment's constructor. Move your code to onActivityCreated() method.
qlife1146 said:
I want to send mail from Navigation Drawer using the intent. First, my MainActivity.
Code:
else if(id==R.id.nav_mail) {
fragment = new MailFragment();
}
and MailFragment.
Code:
public class MailFragment extends Fragment {
public MailFragment() {
Intent email = new Intent(Intent.ACTION_SEND);
email.setType("plain/text");
String[] address = {"********@gmail.com"};
email.putExtra(Intent.EXTRA_EMAIL, address);
email.putExtra(Intent.EXTRA_SUBJECT, "Subject___****");
email.putExtra(Intent.EXTRA_TEXT, "Text___****.\n\n");
startActivity(email);
}
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// TextView textView = new TextView(getActivity());
// textView.setText(R.string.hello_blank_fragment);
// return textView;
// }
}
Run to create crash. The reason why I used to use fragment is because I made the simple screen change function fragment.
If you need more code, comment plz.
Click to expand...
Click to collapse
Creating a new Intent in the constructor is a really bad idea. An example from the android's developer guide
Code:
public class MainActivity extends AppCompatActivity {
public static final String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/** Called when the user taps the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.editText);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}

Categories

Resources