I am new to Android and Java. The following code is to send and wait for receiving SMS. As the process may takes about 3 minutes, I need to have a progressDialog until SMS is received. Could you send me an applet to do this ?
package com.examples.TOLD;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.telephony.SmsManager;
import android.util.Log;
import android.widget.TextView;
public class Sms extends Activity {
/** Called when the activity is first created. */
static TextView smsReceive;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.sms);
Intent i = getIntent();
// Receiving the Data
String reg = i.getStringExtra("reg");
String port = i.getStringExtra("port");
String smsMessage =
"REG=" + reg +
"PORT=" + port;
// Show SMS sent message on screen
TextView smsSend = (TextView) findViewById(R.id.smsSend);
smsSend.setText(smsMessage);
Log.i("smsSend",String.valueOf(smsSend.getText()));
// Send SMS message
SmsManager sm = SmsManager.getDefault();
String number = "5556";
sm.sendTextMessage(number, null, smsMessage, null, null);
// Receive SMS message
smsReceive = (TextView) findViewById(R.id.smsReceive);
}
public static void updateMessageBox(String msg)
{
smsReceive.append(msg);
}
}
Here is another class to receive SMS:
package com.examples.TOLD;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
public class SmsReceiver extends BroadcastReceiver{
public void onReceive(Context context, Intent intent)
{
Bundle bundle=intent.getExtras();
Object[] messages=(Object[])bundle.get("pdus");
SmsMessage[] sms = new SmsMessage[messages.length];
for(int n=0;n<messages.length;n++){
sms[n]=SmsMessage.createFromPdu((byte[]) messages[n]);
}
for(SmsMessage msg:sms){
String num = msg.getOriginatingAddress();
Log.i("SMS sender",num);
if (num.equals("15555215556")) {
Sms.updateMessageBox("\nFrom: " + msg.getOriginatingAddress() +
"\n" + "Message: " + msg.getMessageBody() + "\n");}
}
}
}
I think you can try to reconsider your approach. You can't expect user will be waiting for up to 3 minutes for the SMS. So you code looks right (except the part of the static method cos I explain you later), but once your message is sent, I'd show a message that your app is waiting for the message, and when the message is received in the SmsReceiver, you can communicate with the Sms activity.
But, you shouldn't use that static method to update the content of the activity for several reasons (UI can't be updated in background or most important when the SmsReceiver is fired SMS activity can even non exist). The right way would be sending an intent from the receiver. You can see a detailed step by step example in the pdf contained in this link in the section Receiving SMS messages.
I Don't think sending and receiving should be in the main thread. You can use AsyncTask to receive the message in background. you can show the dialog before starting the task and
close it after recieving
Lookup http://developer.android.com/reference/android/os/AsyncTask.html for painless background threading.
Simply display your progress dialog in OnPreExecute and dismiss it when the task reaches OnPostExecute.
Related
can someone provide me the proper documentation or code to navigate to specific activity by tapping on one signal push notification, i want to open the specific fragment
here is my code where i extened application class and initialize one signal :
package com.example.nasapp;
import android.app.Application;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Parcelable;
import android.util.Log;
import com.example.nasapp.ui.home.HomeFragment;
import com.example.nasapp.ui.information.InformationFragment;
import com.onesignal.OSMutableNotification;
import com.onesignal.OSNotification;
import com.onesignal.OSNotificationAction;
import com.onesignal.OSNotificationOpenedResult;
import com.onesignal.OSNotificationReceivedEvent;
import com.onesignal.OneSignal;
import org.json.JSONException;
import org.json.JSONObject;
public class OneSignalApplication extends Application {
private static final String ONESIGNAL_APP_ID = "e855e254-9b4e-4e6f-a64a-e48db6f35d07";
#Override
public void onCreate() {
super.onCreate();
// Enable verbose OneSignal logging to debug issues if needed.
//OneSignal.setLogLevel(OneSignal.LOG_LEVEL.VERBOSE, OneSignal.LOG_LEVEL.NONE);
// OneSignal Initialization
OneSignal.initWithContext(this);
OneSignal.setAppId(ONESIGNAL_APP_ID);
// promptForPushNotifications will show the native Android notification permission prompt.
// We recommend removing the following code and instead using an In-App Message to prompt for notification permission (See step 7)
OneSignal.promptForPushNotifications();
OneSignal.setNotificationOpenedHandler(new OneSignal.OSNotificationOpenedHandler() {
#Override
public void notificationOpened(OSNotificationOpenedResult result) {
JSONObject data = result.getNotification().getAdditionalData();
Log.i("OneSignalExample", "Notification Data: " + data);
String notification_topic;
if (data != null) {
try {
System.out.println(data.getString("job_id"));
} catch (JSONException e) {
e.printStackTrace();
}
notification_topic = data.optString("notification_topic", "hii");
if (notification_topic != null) {
OneSignal.addTrigger("level", notification_topic);
}
}
}
});
}
}
here is my NotificationServiceExtensionClass:
public class NotificationServiceExtension extends Service implements OneSignal.OSRemoteNotificationReceivedHandler {
#Override
public void remoteNotificationReceived(Context context, OSNotificationReceivedEvent notificationReceivedEvent) {
OSNotification notification = notificationReceivedEvent.getNotification();
// Example of modifying the notification's accent color
OSMutableNotification mutableNotification = notification.mutableCopy();
mutableNotification.setExtender(builder -> {
//... do stuff
builder.setTimeoutAfter(30000);
Intent intent = new Intent();
JSONObject data = notification.getAdditionalData();
// check the data and create intent
intent = new Intent(context, InformationFragment.class);
// or any other depends on data value
intent.putExtra("data", (Parcelable) data);
PendingIntent pendIntent = PendingIntent.getActivity(context,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
builder = builder.setContentIntent(pendIntent);
return builder;
});
JSONObject data = notification.getAdditionalData();
Log.i("OneSignalExample", "Received Notification Data: " + data);
// If complete isn't call within a time period of 25 seconds, OneSignal internal logic will show the original notification
// To omit displaying a notification, pass `null` to complete()
notificationReceivedEvent.complete(mutableNotification);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
In manifest i declare this service class:
<service
android:name=".service.NotificationServiceExtension"
android:permission="android.permission.BIND_JOB_SERVICE"
android:exported="false">
am i missing some code or what am i doing wrong in code ,can please someone help?
I know this was asked numerous times, but I couldn't find the right answer for me.
I'm only in my third semester of my bachelor degree, so not that much knowledge yet.
Currently having my first Android course after I finished my beginner Java course (emphasis on beginner).
Due to Corona there is next to no Tutor support and the script is lacking decent explanations.
Im struggling with implementing my first Broadcast receiver. It's supposed to make a toast when a power cord is plugged in.
I tried a dynamic receiver so I registered the Receiver in my MainActivity as follows:
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.content.Intent;
public class MainActivity extends AppCompatActivity {
[...]
private PowerConnectedReceiver mPowerConnectedReceiver;
public void onResume() {
super.onResume();
IntentFilter powerFilter = new IntentFilter(Intent.ACTION_POWER_CONNECTED );
mPowerConnectedReceiver = new PowerConnectedReceiver();
getApplicationContext().registerReceiver(mPowerConnectedReceiver , powerFilter);
}
#Override
protected void onPause() {
getApplicationContext().unregisterReceiver(mPowerConnectedReceiver);
super.onPause();
}
With the Broadcast Receiver looking as follows and this is where the error pops up. It says for the Context of the Toast that MainActivity is not an enclosed class.
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
import static android.widget.Toast.LENGTH_LONG;
public class PowerConnectedReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(MainActivity.this, "POWER CONNECTED received", LENGTH_LONG ).show();
}
}
This is the way of implementing that is taught in the script.
As I mentioned I am fairly new to programming and this might be something totally obvious, but I'm not seeing it.
The only thing I tried was changing it to MainAcivity.class, but that did nothing.
Thanks for support.
Your code is correct, but in the toast message you have to use context of the receiver i.e the first parameter of the onReceive method.
Update your toast message from:
Toast.makeText(MainActivity.this, "POWER CONNECTED received", LENGTH_LONG ).show();
to
Toast.makeText(context, "POWER CONNECTED received", LENGTH_LONG ).show();
Am new for android . I want send sms after click send button
first i have used sms manager api.
package com.example.smsproject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;`enter code here`
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Page2Activity extends Activity {
Button button;
EditText textPhoneNo;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button) findViewById(R.id.button1);
textPhoneNo = (EditText) findViewById(R.id.mobilenumber);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v){
//String phoneNo = textPhoneNo.getText().toString();
String phoneNo = "tel:xxxxxxxxxx";
String messageText = "SMS FROM ANDROID";
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, messageText, null, null);
Toast.makeText(getApplicationContext(), "SMS Sent Successfully!",
Toast.LENGTH_LONG).show();
}catch (Exception e){
Toast.makeText(getApplicationContext(),
"SMS failed, please try again later ! ",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
}
}
set send_sms permission on android_manifest.xml
i got zero errors but sms not sending. If you have know answer.
please let me know, thanks for reading.
To complete #Android Fanatic answer
If the text is too long, the message does not go away, you have to respect max length depending of encoding.
More information can be found here.
I'd prefer this method
SmsManager sms = SmsManager.getDefault();
ArrayList<String> parts = sms.divideMessage(message);
ArrayList<PendingIntent> sendList = new ArrayList<>();
sendList.add(sentPI);
ArrayList<PendingIntent> deliverList = new ArrayList<>();
deliverList.add(deliveredPI);
sms.sendMultipartTextMessage(phoneNumber, null, parts, sendList, deliverList);
Also SMS Manager doesn't sent messages if the message is longer than 160 for English text, and 70 for 16-bit alphabet text. Try sending small English text to see if it's the case.
(You can sent multiple part messages to send long texts).
String incomming = "9876543210";
android.telephony.SmsManager sms=android.telephony.SmsManager.getDefault();
sms.sendTextMessage(incomming, null,"Here Is Sms", null, null);
Log.d("SMS ready to send", "----FIRST CALL----");
String number = "111111111111"; //ed1.getText().toString();
String message = "Test SMS DATA"; //ed2.getText().toString();
Log.d("SMS ready to send", "----SECOND CALL----"+number);
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(number, null, message, null, null);
Log.d("SMS ready to send", "----THIRD CALL----");
I want to enter an IP address and port of a server using editText in Android studio. When a "connect" button is pressed, the entered information should be saved and be accessible to other activities. I have used the SharedPreferences method for saving the acquired data to be accessible across activities (Is this the best way to do so?). The successful creation of a client socket (handled in the service) is checked in the Connect activity (attached below) by means of (!client.isClosed()).
My problem is that whenever the activity reaches the check in the Connect.java activity, the isclosed is nullified. I assume that the client Socket is thus destroyed when it was created in the Service and called in the Connect.java activity.
Is there a way to create the Socket and keep it alive to be used by various other activities- I require the socket to be kept alive to receive/send messages to a server which will determine to which activity the App should transition. The method of creating and closing sockets in every activity will not work as it will be registered as a new user on the server side- firmware on a module I have no access to.
Any examples/documentation/help would be greatly appreciated.
I am very new to Android App development and Java so please be gentle if my questions are stupid :-)
Thank you very much for any assistance.
This is the service for handling the socket creation.
import android.app.IntentService;
import android.content.Intent;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.StrictMode;
import android.util.Log;
import java.io.IOException;
import java.net.Socket;
public class SocketService extends IntentService
{
public Socket client;
public String ClientIP;
public Integer ClientPORT=0;
public SocketService()
{
super("SocketService");
}
#Override
protected void onHandleIntent(Intent Socketintent)
{
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
SharedPreferences savednotes= getSharedPreferences("Socket_NAME",
Context.MODE_MULTI_PROCESS);
ClientIP=savednotes.getString("IP_NAME",null); // Get the IP address
ClientPORT=savednotes.getInt("PORT_NAME",0); // Get the Port number
try
{
Log.d("IP", "Master IP address:" + ClientIP); // Debug to see
variables in Shared preferences
Log.d("PORT", "Port number: " + ClientPORT); // Debug to see
variables in Shared preferences
if ((ClientIP) != null)
{
if ((ClientPORT) != null)
{
client = new Socket(ClientIP, ClientPORT); // Create the Socket
}
}
} catch (IOException e)
{
e.printStackTrace();
try {
client.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
This is the Connect.java activity:
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.PrintWriter;
import java.net.Socket;
public class Connect extends AppCompatActivity
{
public Socket client;
private EditText etIP, etPORT;
private TextView status,IPs;
private Button buttonCON;
public int port=0;
public String IP;
SharedPreferences savednotes;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.activity_connect);
etIP = (EditText)findViewById(R.id.editTextIP);
etPORT = (EditText)findViewById(R.id.editText2);
buttonCON= (Button)findViewById(R.id.buttonCON);
status= (TextView)findViewById(R.id.textStatus);
IPs=(TextView)findViewById(R.id.textViewIP);
status.setText("Disconnected");
buttonCON.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
port = Integer.parseInt(etPORT.getText().toString());
IP= etIP.getText().toString();
IPs.setText(IP);
savednotes=
getApplicationContext().getSharedPreferences("Socket_NAME",
Context.MODE_MULTI_PROCESS);
SharedPreferences.Editor editor= savednotes.edit();
editor.putString("IP_NAME",IP);
editor.apply();
editor.putInt("PORT_NAME",port);
editor.apply();
Intent Socketintent= new Intent(Connect.this, SocketService.class);
startService(Socketintent);
int i = 0xFF00EE00;
status.setTextColor(i);
status.setText("Connected");
if (!client.isClosed())
{
Intent relay= new Intent(Connect.this, Relay.class);
startActivity(relay);
finish();
}
}
});
}
}
An IntentService is not a suitable solution for your objective. An IntentService is destroyed as soon as onHandleIntent() returns.
Most likely, you do not need any sort of Service here. A Service is for when you want to be doing work when you have no UI in the foreground, and that does not sound like your case here ("Keeping a Client Socket alive between activities"). An ordinary Java singleton would work, so long as you are very careful not to introduce memory leaks.
The method of creating and closing sockets in every activity will not work as it will be registered as a new user on the server side- firmware on a module I have no access to.
Bear in mind that your process does not live forever. Eventually, you will need to create a new socket.
I using a tutorial from tutsplus.com on building a twitter client for Android. I've built the entire application and when I run it, the following error appears in logcat for Eclipse.
android.os.NetworkOnMainThreadException -- reading a few things, it has to deal with the API level I'm calling. Currently I'm building for 4.0.3 which is API 15. After API 11, you are not allowed to do network calls in the same thread as the UI. The reason behind this is not to stall or crash the UI. Networking calls must be in an AsyncTask or Service.
Long and short of my question/problem/issue is that the tutorial maker is of no help to correct the problem, so that's why I'm here. I'm posting the code below, in hopes that someone can help me move the network portion into an AsyncTask or Service.
package com.jasonsdesign.tweetxy;
import twitter4j.ProfileImage;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
public class TweetxyActivity extends Activity implements OnClickListener {
/**developer account key for this app*/
public final static String TWIT_KEY = "";
/**developer secret for the app*/
public final static String TWIT_SECRET = "";
/**app url*/
public final static String TWIT_URL = "tweetxy-android:///";
private String LOG_TAG = "TweetxyActivity";
/**Twitter instance*/
private Twitter tweetxyTwitter;
/**request token for accessing user account*/
private RequestToken tweetxyRequestToken;
/**shared preferences to store user details*/
private SharedPreferences tweetxyPrefs;
/**main view for the home timeline*/
private ListView homeTimeline;
/**database helper for update data*/
private TweetxyDataHelper timelineHelper;
/**update database*/
private SQLiteDatabase timelineDB;
/**cursor for handling data*/
private Cursor timelineCursor;
/**adapter for mapping data*/
private UpdateAdapter timelineAdapter;
/**broadcast receiver for when new updates are available*/
private BroadcastReceiver tweetxyStatusReceiver;
//set the profile image display
ProfileImage.ImageSize imageSize = ProfileImage.NORMAL;
/*
* onCreate behaves differently on first run and subsequent runs
* - if first run take to Twitter sign in page to grant the app permission
* - subsequent runs fetch and present the user home timeline
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//get the preferences
tweetxyPrefs = getSharedPreferences("TweetxyPrefs", 0);
//find out if the user preferences are set
if(tweetxyPrefs.getString("user_token", null)==null) {
//no user preferences so prompt to sign in
setContentView(R.layout.main);
//get a twitter instance for authentication
tweetxyTwitter = new TwitterFactory().getInstance();
//pass developer key and secret
tweetxyTwitter.setOAuthConsumer(TWIT_KEY, TWIT_SECRET);
//try to get request token
try
{
//get authentication request token
tweetxyRequestToken = tweetxyTwitter.getOAuthRequestToken(TWIT_URL);
}
catch(TwitterException te) { Log.e(LOG_TAG, "TE "+te.getMessage()); }
//setup button for click listener
Button signIn = (Button)findViewById(R.id.signin);
signIn.setOnClickListener(this);
}
else
{
//user preferences are set - get timeline
setupTimeline();
}
}
/**
* Click listener handles sign in and tweet button presses
*/
public void onClick(View v) {
//find view
switch(v.getId()) {
//sign in button pressed
case R.id.signin:
//take user to twitter authentication web page to allow app access to their twitter account
String authURL = tweetxyRequestToken.getAuthenticationURL();
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authURL)));
break;
//user has pressed tweet button
case R.id.tweetbtn:
//launch tweet activity
startActivity(new Intent(this, TweetxyTweet.class));
break;
default:
break;
}
}
/*
* onNewIntent fires when user returns from Twitter authentication Web page
*/
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
//get the retrieved data
Uri twitURI = intent.getData();
//make sure the url is correct
if(twitURI!=null && twitURI.toString().startsWith(TWIT_URL))
{
//is verification - get the returned data
String oaVerifier = twitURI.getQueryParameter("oauth_verifier");
//attempt to retrieve access token
try
{
//try to get an access token using the returned data from the verification page
AccessToken accToken = tweetxyTwitter.getOAuthAccessToken(tweetxyRequestToken, oaVerifier);
//add the token and secret to shared prefs for future reference
tweetxyPrefs.edit()
.putString("user_token", accToken.getToken())
.putString("user_secret", accToken.getTokenSecret())
.commit();
//display the timeline
setupTimeline();
}
catch (TwitterException te)
{ Log.e(LOG_TAG, "Failed to get access token: "+te.getMessage()); }
}
}
/**
* setupTimeline displays the user's main home Twitter timeline
*/
private void setupTimeline() {
//set the layout
setContentView(R.layout.timeline);
//setup onclick listener for tweet button
LinearLayout tweetClicker = (LinearLayout)findViewById(R.id.tweetbtn);
tweetClicker.setOnClickListener(this);
//retrieve the timeline
try
{
//get reference to the list view
homeTimeline = (ListView)findViewById(R.id.homeList);
//instantiate database helper
timelineHelper = new TweetxyDataHelper(this);
//get the database
timelineDB = timelineHelper.getReadableDatabase();
//query the database, most recent tweets first
timelineCursor = timelineDB.query("home", null, null, null, null, null, "update_time DESC");
//manage the updates using a cursor
startManagingCursor(timelineCursor);
//instantiate adapter
timelineAdapter = new UpdateAdapter(this, timelineCursor);
//apply the adapter to the timeline view
//this will make it populate the new update data in the view
homeTimeline.setAdapter(timelineAdapter);
//instantiate receiver class for finding out when new updates are available
tweetxyStatusReceiver = new TwitterUpdateReceiver();
//register for updates
registerReceiver(tweetxyStatusReceiver, new IntentFilter("TWITTER_UPDATES"));
//start the service for updates now
this.getApplicationContext().startService(new Intent(this.getApplicationContext(), TimelineService.class));
}
catch(Exception te) { Log.e(LOG_TAG, "Failed to fetch timeline: "+te.getMessage()); }
}
/**
* Class to implement broadcast receipt for new updates
*/
class TwitterUpdateReceiver extends BroadcastReceiver
{
/**
* When new updates are available, a broadcast is received here
*/
#Override
public void onReceive(Context context, Intent intent) {
//delete db rows
int rowLimit = 100;
if(DatabaseUtils.queryNumEntries(timelineDB, "home")>rowLimit) {
String deleteQuery = "DELETE FROM home WHERE "+BaseColumns._ID+" NOT IN " +
"(SELECT "+BaseColumns._ID+" FROM home ORDER BY "+"update_time DESC " +
"limit "+rowLimit+")";
timelineDB.execSQL(deleteQuery);
}
timelineCursor = timelineDB.query("home", null, null, null, null, null, "update_time DESC");
startManagingCursor(timelineCursor);
timelineAdapter = new UpdateAdapter(context, timelineCursor);
homeTimeline.setAdapter(timelineAdapter);
}
}
/*
* When the class is destroyed, close database and service classes
*/
#Override
public void onDestroy() {
super.onDestroy();
try
{
//stop the updater service
stopService(new Intent(this, TimelineService.class));
//remove receiver register
unregisterReceiver(tweetxyStatusReceiver);
//close the database
timelineDB.close();
}
catch(Exception se) { Log.e(LOG_TAG, "unable to stop service or receiver"); }
}
}
What do you need besides what https://developer.android.com/reference/android/os/AsyncTask.html provides? Do you have a specific question regarding the usage of AsyncTask?
You take the offending line and put it inside doInBackground(). If it has a result you either put the result handling code in doInBackground(), if it does not manipulate the UI. If it does make changes to the UI, you put it in onPostExecute().
Then you replace the line that threw the exception with:
new MyTask().execute(param);
Keep in mind that the code after this is executed immediately.
I don't see a need for your question to be held up, most of the issues you face at the moment are solvable through the AsyncTask use that is so well documented over Here.
I'd suggest you don't use the tutorial as a framework to your app/project but rather use it as a guide to know how to set your own project up. It'll be way better if you create your own AsyncTask and use that to get data from the network as getting network related data in a main task or most tasks besides AsynTasks is usually frowned upon due to the exceptions it throws.