Socket Programming with Broadcast Recevier - android

I am developing Android application(online marketing), within this project i am using socket programming for communication with server, when i communicate with server if server does not give me any response within 30 sec then my asynctask will close automatically, but now problem is i want to save server response in sqlite on receiving response from server please provide me the necessary help thank
you in advance.
Here is My Asyntask :
public class SendToserver extends AsyncTask<Integer, Integer, Integer>
{
int iReturn;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
progressDialog(Registartion.this, "Please Wait...");
super.onPreExecute();
}
#Override
protected Integer doInBackground(Integer... params) {
// TODO Auto-generated method stub
ServerData = runm(IMEINo);
if (ServerData.equalsIgnoreCase("IsNull"))
{
iReturn = 2;
}
else {
iReturn = 1;
}
return iReturn;
}
#Override
protected void onPostExecute(Integer result) {
// TODO Auto-generated method stub
if (iReturn == 1)
{
String ServerIP = edtServerIpAddress.getText().toString();
String ServerPort = edtServerPort.getText().toString();
registartionModel = new RegistartionModel();
registartionModel.setServerIPAdreess(ServerIP);
registartionModel.setPort(ServerPort);
registrationDb = new RegistrationDb(getApplicationContext());
registrationDb.open();
registrationDb.insertData(registartionModel);
registrationDb.close();
Intent i = new Intent(getBaseContext(), LoginActivity.class);
startActivity(i);
Registartion.this.finish();
System.gc();
}
else if (iReturn == 2)
{
showDialogBox("Please Input Correct Server IP and Port");
}
super.onPostExecute(result);
}
}
My Server Communication Method(runm):
#SuppressLint("NewApi")
public String runm(String DId)
{
try {
socket = new Socket(SERVER_IP, SERVERPORT);
out = new PrintStream(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.write((DId + "|" +"REG").getBytes());
ServerData = in.readLine();
System.err.println("Server Data in Runm :- " + ServerData);
if(ServerData == null || ServerData.equalsIgnoreCase(""))
{
ServerData="IsNull";
}
}
catch (NetworkOnMainThreadException e)
{
ServerData = "IsNull";
}catch (IOException ex) {
ServerData = "IsNull";
}
return ServerData;
}
Should i use Broadcast Receiver ?

Related

My application is working on emulator but not on real devices

i am using simple asynctask function for getting values from mysql database through json.it was working fine with emulator but if i am trying from the mobile i am getting error. like Java.lang.NullPointerExceprtion:Attempt to invke virtual metho 'java.lang.string.java.lang.stringbuilder.toString() on a null object reference.
I tried with new project but result is same. this application is not working in all the devices except emulator. can you help me on this.
My Code is -
public class MainActivity extends AppCompatActivity {
private static final String Latest_Products7 = "Questions";
JSONArray productsArray7 = null;
public static final int CONNECTION_TIMEOUT7=100000;
public static final int READ_TIMEOUT7=150000;
HashMap<String,ArrayList<WorldPopulation>> hasmap = new HashMap<String,ArrayList<WorldPopulation>>();
ArrayList<WorldPopulation> arraylist7 = null;
StringBuilder result7;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new AsyncLogin7().execute();
}
private class AsyncLogin7 extends AsyncTask<String, String, StringBuilder> {
ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
HttpURLConnection conn7;
URL url7 = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected StringBuilder doInBackground(String... params) {
try {
// Enter URL address where your php file resides
url7 = new URL("http:/Samplesite/****/somephp.php");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn7 = (HttpURLConnection)url7.openConnection();
conn7.setReadTimeout(READ_TIMEOUT7);
conn7.setConnectTimeout(CONNECTION_TIMEOUT7);
conn7.setRequestMethod("POST");
// setDoInput and setDoOutput method depict handling of both send and receive
conn7.setDoInput(true);
conn7.setDoOutput(true);
// Append parameters to URL
Uri.Builder builder7 = new Uri.Builder().appendQueryParameter("reg_id", "hai") ;
String query7 = builder7.build().getEncodedQuery();
// Open connection for sending data
OutputStream os7 = conn7.getOutputStream();
BufferedWriter writer7 = new BufferedWriter(new OutputStreamWriter(os7, "UTF-8"));
writer7.write(query7);
writer7.flush();
writer7.close();
os7.close();
conn7.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
int response_code7 = conn7.getResponseCode();
// Check if successful connection made
if (response_code7 == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input7 = conn7.getInputStream();
BufferedReader reader7 = new BufferedReader(new InputStreamReader(input7));
result7 = new StringBuilder();
String line7;
while ((line7 = reader7.readLine()) != null) {
result7.append(line7);
}
// Pass data to onPostExecute method
}
} catch (IOException e) {
e.printStackTrace();
} finally {
conn7.disconnect();
}
return result7;
}
#Override
protected void onPostExecute(StringBuilder result7) {
super.onPostExecute(result7);
Log.e("dai",result7.toString());
Toast.makeText(MainActivity.this,result7.toString(),Toast.LENGTH_LONG).show();
pdLoading.dismiss();
/* Intent intnt = new Intent(Checklist_activity.this,Task_main.class);
intnt.putExtra("task",hasmap);
startActivity(intnt);*/
}
}
}
Change
try {
int response_code7 = conn7.getResponseCode();
// Check if successful connection made
if (response_code7 == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input7 = conn7.getInputStream();
BufferedReader reader7 = new BufferedReader(new InputStreamReader(input7));
result7 = new StringBuilder();
String line7;
while ((line7 = reader7.readLine()) != null) {
result7.append(line7);
}
// Pass data to onPostExecute method
}
} catch (IOException e) {
e.printStackTrace();
} finally {
conn7.disconnect();
}
return result7;
To
try {
int response_code7 = conn7.getResponseCode();
result7 = new StringBuilder();
// Check if successful connection made
if (response_code7 == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input7 = conn7.getInputStream();
BufferedReader reader7 = new BufferedReader(new InputStreamReader(input7));
String line7;
while ((line7 = reader7.readLine()) != null) {
result7.append(line7);
}
// Pass data to onPostExecute method
}
} catch (IOException e) {
e.printStackTrace();
} finally {
conn7.disconnect();
}
return result7;
Try something like this
Log.e("dai",MainActivity.this.result7.toString());
Toast.makeText(MainActivity.this,MainActivity.this.result7.toString(),Toast.LENGTH_LONG).show();
OR
#Override
protected void onPostExecute(StringBuilder result) {
super.onPostExecute(result);
Log.e("dai",result.toString());
Toast.makeText(MainActivity.this,result.toString(),Toast.LENGTH_LONG).show();
pdLoading.dismiss();
/* Intent intnt = new Intent(Checklist_activity.this,Task_main.class);
intnt.putExtra("task",hasmap);
startActivity(intnt);*/
}
}

UDP holepunching: PC-to-Android UDP connection does not work with nonlocal addresses

I wrote a simple UDP transfer between an Android App and Python Server. I know that the system is working because when I try to connect on a local ip address (192.168.X.X), the correct message is sent and recieved. However, this does not work when I try to use a public IP address. Does anyone know why and how I can try to fix this?
I am trying to implement UDP holepunching, having the server act as the target client of the Android one, but I cannot get the 2nd client's UDP packet to the Android one, it never gets picked up on the Android's side. Would having a 2nd machine act as the 2nd client fix this, or is my code incomplete?
Does my provider (T-Mobile) matter for UDP packet communication?
Client (Android):
public class CustomizeGatewayActivity extends ActionBarActivity {
AsyncUDPReceiver aReceive = null;
static TextView recieve = null;
public static class PlaceholderFragment extends Fragment {
EditText addressText, portText, messageText;
Button udpsend, tcpsend;
Socket socket = null;
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment_customize_gateway, container, false);
recieve = (TextView) rootView.findViewById(R.id.textView1);
addressText = (EditText) rootView.findViewById(R.id.editText1);
messageText = (EditText) rootView.findViewById(R.id.editText3);
udpsend = (Button) rootView.findViewById(R.id.UDP);
udpsend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
AsyncUDPSend aSend = new AsyncUDPSend(addressText.getText().toString(), messageText.getText().toString());
aSend.execute();
}
});
public class AsyncUDPSend extends AsyncTask<Void, Void, Void> {
String address = "";
String message = "";
String response = "";
AsyncUDPSend(String addr, String mes) {
address = addr;
message = mes;
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
DatagramSocket dsocket = null;
try {
dsocket = new DatagramSocket();
dsocket.setSoTimeout(10000);
InetAddress dest = InetAddress.getByName(address);
DatagramPacket packet = new DatagramPacket(message.getBytes(), message.length(), dest, 5001);
dsocket.send(packet);
System.out.println("Sent");
byte[] resp = new byte[1024];
DatagramPacket recv = new DatagramPacket(resp, resp.length);
System.out.println("Waitng for Response");
dsocket.receive(recv);
System.out.println("Received");
response = new String(recv.getData());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
System.out.println(response);
} finally {
if (dsocket != null) {
dsocket.close();
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
recieve.setText(response);
super.onPostExecute(result);
}
}
#Override
protected void onResume() {
super.onResume();
aReceive = new AsyncUDPReceiver();
aReceive.start();
}
#Override
protected void onPause() {
super.onPause();
aReceive.kill();
}
public class AsyncUDPReceiver extends Thread {
boolean keepRunning = true;
String response = "";
Runnable updateText = new Runnable(){
public void run() {
if(aReceive == null && recieve == null)
return;
recieve.setText(response);
}
};
public void run() {
android.os.Debug.waitForDebugger();
System.out.println("running");
DatagramSocket dsock = null;
byte[] message = new byte[1024];
DatagramPacket dpack = new DatagramPacket(message, message.length);
try {
dsock = new DatagramSocket(5002);
System.out.println(dsock.toString());
while(keepRunning) {
dsock.receive(dpack);
response = new String(dpack.getData());
System.out.println(response);
runOnUiThread(updateText);
}
} catch (SocketException e) {
// TODO Auto-generated catch block
response = "SocketException: " + e.toString();
System.out.println(response);
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
response = "IOException: " + e.toString();
System.out.println(response);
e.printStackTrace();
} finally {
if(dsock != null)
dsock.close();
}
}
public void kill() {
keepRunning = false;
}
}
}
Server (Python):
class ThreadedUDPRequestHandler(socketserver.BaseRequestHandler):
def handle(self):
data = self.request[0].strip().decode("utf-8")
print("{} Recieved: ".format(self.client_address) + data)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
response = data.upper()
sock.sendto(bytes(response, "utf-8"), self.client_address)
print("{} Sent: {}".format(self.client_address,response))
class ThreadedUDPServer(socketserver.ThreadingMixIn, socketserver.UDPServer):
pass
if __name__ == "__main__":
# Port 0 means to select an arbitrary unused port
HOST, PORT = "", 5000
udpserver = ThreadedUDPServer((HOST,PORT+1), ThreadedUDPRequestHandler)
udp_thread = threading.Thread(target=udpserver.serve_forever)
udp_thread.daemon = True
udp_thread.start()
print("UDP serving at port", PORT+1)
while True:
pass
udpserver.shutdown()
Are you supplying the expected value to InetAddress.getByName(address);
Also since you are trying to do something in background,it will be better if you run a service with wake lock so that you eliminate errors caused due to killing of process.

How to use multiple AsyncTasks

I'm coding the client side of an Android application which uses sockets. Since I'm new with AsyncTask, I coded something simple to test my understanding. Here is what I have, it seems to be correct:
public class Messaggi extends ActionBarActivity implements OnClickListener {
LinearLayout mLayout;
ScrollView scroll;
EditText writeMessage;
Button send;
Socket connection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_messaggi);
mLayout = (LinearLayout) findViewById(R.id.linearVertical);
scroll = (ScrollView) findViewById(R.id.scrollView1);
writeMessage= (EditText)findViewById(R.id.ScriviMessaggio);
send= (Button)findViewById(R.id.invia);
send.setOnClickListener(this);
LavoraDietro asd = new LavoraDietro();
asd.execute();
}
#Override
public void onClick(View v) {
}
private void updateScroll(){
scroll.post(new Runnable() {
#Override
public void run() {
scroll.fullScroll(View.FOCUS_DOWN);
}
});
}
private TextView createNewTextView(String text) {
final LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
final TextView textView = new TextView(this);
textView.setLayoutParams(lparams);
textView.setText("Client: " + text);
return textView;
}
private class LavoraDietro extends AsyncTask<Void, Void, Boolean> {
String mex;
#Override
protected Boolean doInBackground(Void... params){
try {
InetAddress local = InetAddress.getByName("192.168.1.79");
Socket connection= new Socket(local , 7100);
DataOutputStream output = new DataOutputStream(connection.getOutputStream());
output.writeUTF("Client: Server prova");
output.flush();
DataInputStream input = new DataInputStream(connection.getInputStream());
mex= input.readUTF();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}catch(Exception e){
e.printStackTrace();
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if(result == true){
mLayout.addView(createNewTextView("Sono connesso al server"));
mLayout.addView(createNewTextView("I canali sono aperi.."));
mLayout.addView(createNewTextView(mex));
updateScroll();
}
else{
mLayout.addView(createNewTextView("ERRORE CONNESSIONE AL SERVER "));
updateScroll();
}
}
}
}
When the connection to the server is established, the client sends a test meesage and the server should send the same message to the client, where it is printed.
But my task is to establish the connection immediatly when the app is opened and send a message only when the button "send" is pressed. Is possible to create multiple AsyncTasks and make them work at the same time without crashing the application? If yes, can you please post an example of how can I do this?
EDITED CODE
This is my new code:
public class Messaggi extends ActionBarActivity implements OnClickListener {
LinearLayout mLayout;
ScrollView scroll;
EditText writeMessage;
Button send;
Socket connection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_messaggi);
mLayout = (LinearLayout) findViewById(R.id.linearVertical);
scroll = (ScrollView) findViewById(R.id.scrollView1);
writeMessage= (EditText)findViewById(R.id.ScriviMessaggio);
send= (Button)findViewById(R.id.invia);
send.setOnClickListener(this);
LavoraDietro asd = new LavoraDietro();
asd.execute();
}
#Override
public void onClick(View v) {
CliccaInvia asd123 = new CliccaInvia();
asd123.execute(connection);
}
private void updateScroll(){
scroll.post(new Runnable() {
#Override
public void run() {
scroll.fullScroll(View.FOCUS_DOWN);
}
});
}
private TextView createNewTextView(String text) {
final LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
final TextView textView = new TextView(this);
textView.setLayoutParams(lparams);
textView.setText("Client: " + text);
return textView;
}
private class LavoraDietro extends AsyncTask<Void, Void, Socket> {
String mex;
#Override
protected Socket doInBackground(Void... params){
try {
InetAddress local = InetAddress.getByName("192.168.1.79");
connection= new Socket(local , 7100);
DataInputStream input = new DataInputStream(connection.getInputStream());
mex = input.readUTF();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
return connection;
}
#Override
protected void onPostExecute(Socket result) {
super.onPostExecute(result);
if(result != null){
mLayout.addView(createNewTextView("Sono connesso al server"));
mLayout.addView(createNewTextView("I canali sono aperi.."));
mLayout.addView(createNewTextView(mex));
updateScroll();
}
else{
mLayout.addView(createNewTextView("ERRORE CONNESSIONE AL SERVER "));
updateScroll();
}
}
}
private class CliccaInvia extends AsyncTask<Socket, Void, Boolean>{
#Override
protected Boolean doInBackground(Socket... params) {
try {
DataOutputStream output = new DataOutputStream(connection.getOutputStream());
output.writeUTF("Client: Server prova");
output.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if(result == true){
mLayout.addView(createNewTextView("Message Sent"));
aggiornaScroll();
}
else{
mLayout.addView(createNewTextView("Error sending Mex "));
aggiornaScroll();
}
}
}
But this doesn't work.. :(
Well if you need to spawn a lot of tasks and keep track of them all you could do something like this
List<LavoraDietro> tasks = new ArrayList<LavoraDietro>();
LavoraDietro task = new LavoraDietro();
task.execute;
tasks.add(task);
then in your LavoraDietro in the onPostExecute
tasks.remove(this);
But there is a million different ways you could make connections if you want. I recommend Apache's library. http://hc.apache.org/httpclient-3.x/
Here is an example of how you might make a connection, just call this function from inside the background of your task.
public static InputStream getHTTPRequest(String url, ArrayList<NameValuePair> parameters, ArrayList<NameValuePair> headers)
{
final String TAG = "getHTTPRequest";
HttpGet getRequest = new HttpGet(url);
// attach all and any params
if (parameters != null && parameters.size() > 0)
{
HttpParams params = getRequest.getParams();
for (NameValuePair param : parameters)
{
params.setParameter(param.getName(), param.getValue());
}
getRequest.setParams(params);
}
// attach all and any headers
if (headers != null && headers.size() > 0)
{
for (NameValuePair header : headers)
{
getRequest.addHeader(header.getName(), header.getValue());
}
}
getRequest.addHeader("Content-type", "application/json");
getRequest.addHeader("Accept", "application/json");
DefaultHttpClient client = new DefaultHttpClient();
try
{
HttpResponse getResponse = client.execute(getRequest);
final int statusCode = getResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK)
{
Log.d(TAG, "status not ok");
Log.d(TAG, "status = " + Integer.toString(statusCode));
Log.d(TAG, "url = " + getRequest.getURI().toString());
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
Log.d(TAG, "returning valid content");
return getResponseEntity.getContent();
} catch (IOException e)
{
Log.d(TAG, "IOException: getRequest.abort");
getRequest.abort();
}
return null;
}

how to show toast in getDataTaskmethod? [duplicate]

This question already has an answer here:
how to fix getDataTask method error?
(1 answer)
Closed 9 years ago.
this is my code below which work perfectly only problem is not show toast mesage code is blast i want to display toast mesage if Status is 0 in this line if (status.equals("1"))
show toast message but code is blast if i comment Toast then code run perfectly help me what do i do??
public class thirdstep extends Activity {
ListView listCategory;
String status;
String message;
String MenuSelect;
ProgressBar prgLoading;
long Cat_ID;
String Cat_name;
String CategoryAPI;
int IOConnect = 0;
TextView txtAlert;
thirdstepAdapter cla;
static ArrayList<String> Category_ID = new ArrayList<String>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_list2);
ImageButton btnback = (ImageButton) findViewById(R.id.btnback);
listCategory = (ListView) findViewById(R.id.listCategory2);
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
txtAlert = (TextView) findViewById(R.id.txtAlert);
cla = new thirdstepAdapter(thirdstep.this);
new getDataTask().execute();
listCategory.setAdapter(cla);
btnback.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
});
Intent iGet = getIntent();
Cat_ID = iGet.getLongExtra("category_id", 0);
Cat_name = iGet.getStringExtra("category_name");
Toast.makeText(this, Cat_ID + Cat_name, Toast.LENGTH_SHORT).show();
MenuSelect = Utils.MenuSelect;
listCategory.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Intent iMenuList = new Intent(thirdstep.this,
fourthscreen.class);
iMenuList.putExtra("Cat_ID",Cat_ID);
iMenuList.putExtra("Menuitem", Category_ID.get(position));
startActivity(iMenuList);
}
});
}
void clearData() {
Category_ID.clear();
Category_name.clear();
Category_image.clear();
}
public class getDataTask extends AsyncTask<Void, Void, Void>{
getDataTask(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(0);
txtAlert.setVisibility(8);
}
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
parseJSONData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
prgLoading.setVisibility(8);
if((Category_ID.size() > 0) || IOConnect == 0){
listCategory.setVisibility(0);
listCategory.setAdapter(cla);
}else{
txtAlert.setVisibility(0);
}
}
}
public void parseJSONData() {
CategoryAPI = Utils.MenuList + Cat_ID;
clearData();
try {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams
.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(CategoryAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(
atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null) {
str += line;
}
JSONObject json = new JSONObject(str);
JSONObject json2 = new JSONObject(str);
status = json2.getString("status");
message = json2.getString("message");
if (status.equals("1")) {
JSONObject data = json.getJSONObject("data");
JSONArray school = data.getJSONArray("menu_groups");
for (int i = 0; i < school.length(); i++) {
JSONObject object = school.getJSONObject(i);
Category_ID.add(object.getString("id"));
Category_name.add(object.getString("title"));
Category_image.add(object.getString("image"));
}
}
else
{
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
IOConnect = 1;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Your toast message is within the parseJsonData method which is called from the doInBackground method of your asynctask.
You can not update the user interface thread from a background thread.
You have two options here
1) You can publish the progress publishProgress(1) of the thread passing in an integer value to be used as a flag which you can pick up on in the onPublishProgress listener and show your toast there
or
2) As your method has finished by this point then make the parseJsonData set an integer variable global to the asynctask and in the onPostExecute method pass something back to the listener to indicate that a toast needs to be shown
Update based on comments
Replace
{
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
with
{
publishProgress(1);
}
Add the missing onProgressUpdate() method to your asynctask
#Override
protected void onProgressUpdate(Integer... percent) {
//Call your listeners.onProgressUpdate(percent) here and show the
//Or
super.onProgressUpdate(percent);
if (percent[0] == 1){
Toast.makeText(thirdstep.this, message, Toast.LENGTH_SHORT).show();
}
}
I'm not here to write your code for you. Do some research on how to properly write an async task and publish progress
Here is a good starting point
http://androidresearch.wordpress.com/2012/03/17/understanding-asynctask-once-and-forever/
You should be aware of orientation changes and how that will effect your asynctask (I avoid the pitfals of this by using a fragment
This is the design pattern I use for async tasks
http://www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html
But for handling web services, be nice to your users and let the android system work out when to download data etc and don't drain their battery and use a sync adapter with an intentservice instead of an asynctask. There are already too many crappy apps out there that take the asynctask approach for consuming web services. Please don't add yours to the list
Do it this way
http://developer.android.com/training/sync-adapters/creating-sync-adapter.html
It's a lot of extra learning curve but your a programmer right? You should be giving your users the best possible experience.
BTW You are getting down votes because you are demanding code to be written for you. I'm hoping this is just a language barrier and not an attitude problem.
Surround your Toast with this
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getBaseContext(), message, Toast.LENGTH_SHORT).show();
}
});

Android: AsyncTask and reading internet data

I have written a code to download some data from internet. Than i wanted to put it into asyncTask. And after that downloading stopped working. It looks like it cant finish try{} part so skips to exeption.
From main activity "Nekaj" i call loadData() class, which extends AsyncData. From there i call "oto" class inside try command. "oto" class is used to read stuff from internet and returns array of strings. This worked when i called oto class directly from "Nekaj"class. What did I do wrong with using AsyncTask?
Here is the code:
public class Nekaj extends Activity {
TextView Tkolo, Tbroj1;
String[] brojevi_varijabla;
String privremena_varijabla = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.bez_provjere_739);
Tkolo = (TextView) findViewById(R.id.Xkolo);
Tbroj1 = (TextView) findViewById(R.id.Xbroj1);
/*
* try { privremena_varijabla = test.kolo_739();
* Tkolo.setText(privremena_varijabla); } catch (Exception e) { // TODO
* Auto-generated catch block e.printStackTrace(); }
*/
new loadData().execute();
}
public class loadData extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
Oto test = new Oto();
try {
brojevi_varijabla = test.brojevi_739();
if (Integer.valueOf(brojevi_varijabla[0]) > 10) {
Tbroj1.setText("" + brojevi_varijabla[0]);
} else {
Tbroj1.setText(" " + brojevi_varijabla[0]);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
public class Oto {
public String[] brojevi_739() throws Exception {
int i = 0;
int uvjet = 0;
int varijabla = 0;
char[] znak = { '>', '<' };
BufferedReader in = null;
String data[] = null;
String provjera = "date-info";
int[] polje = new int[2];
try {
HttpClient klijent = new DefaultHttpClient();
URI webstranica = new URI(
"https://www.aaa.bb");
HttpGet zahtjev = new HttpGet();
zahtjev.setURI(webstranica);
HttpResponse odgovor = klijent.execute(zahtjev);
in = new BufferedReader(new InputStreamReader(odgovor
.getEntity().getContent()));
StringBuffer brojevi = new StringBuffer("");
String brojevi_string = null;
String neki_string = null;
String red = "";
in.skip(21000);
while ((red = in.readLine()) != null) {
varijabla = red.indexOf(provjera);
if (varijabla != -1) {
// 1. KOLO
if (uvjet == 0) { // onda sadrži taj
// substring
// !!!!
red = in.readLine(); // sada string red sadrži ono
// što
// želim, još moram samo to
// izrezati!!
do {
if (i == 0) {
varijabla = red.indexOf(znak[i]);
}
else {
varijabla = red.indexOf(znak[i], polje[0]);
}
if (varijabla != -1) // ako taj znak postoji u
// stringu
{
if (i == 0) {
polje[i] = varijabla + 1;
}
else {
polje[i] = varijabla;
}
i++;
}
} while (i <= 1);
neki_string = red.substring(polje[0], polje[1]);
Tkolo.setText(neki_string);
provjera = "Dobitna kombinacija";
uvjet++;
continue;
}
}
}
in.close();
brojevi_string = brojevi.toString();
data = brojevi_string.split("\n");
return data;
} finally {
if (in != null) {
try {
in.close();
return data;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}}
What you are doing wrong is Tbroj1.setText() inside the doInBackground() method. What you have to do is to use the onPostExecute method to post your data on the UI:
public class loadData extends AsyncTask<String, Integer, Boolean> {
protected Long doInBackground(String... arg0) {
Oto test = new Oto();
Boolean result = false;
try {
brojevi_varijabla = test.brojevi_739();
result = true;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
protected void onPostExecute(Boolean result) {
if(result){
if (Integer.valueOf(brojevi_varijabla[0]) > 10) {
Tbroj1.setText("" + brojevi_varijabla[0]);
} else {
Tbroj1.setText(" " + brojevi_varijabla[0]);
}
}
}
}
Actually, You are trying to update UI in doInBackGround() of your AsyncTask, so its not allowed (doInBack.. runs in non UI Thread..), So put the UI updation code in onPostExecute() of AsyncTask..
Try this and let me know what happen..
public class loadData extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
Oto test = new Oto();
try {
brojevi_varijabla = test.brojevi_739();
if(brojevi_varijabla != null)
return brojevi_varijabla[0];
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result)
{
if(result != null)
{
if (Integer.valueOf(result) > 10) {
Tbroj1.setText("" + result;
} else {
Tbroj1.setText(" " + result);
}
}
}
}
use onPostExecute(Void result1) {}
to catch the result and perform the action required over there
You can't manipulate UI elements directly on a non-UI (background) thread, which is where doInBackground() always runs. The usual way of using AsyncTask is to get the data in doInBackground(), return it as a value, and then process the UI changes in onPostExecute(). For example:
public class loadData extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... arg0) {
Oto test = new Oto();
try {
brojevi_varijabla = test.brojevi_739();
if (Integer.valueOf(brojevi_varijabla[0]) > 10) {
return "" + brojevi_varijabla[0];
} else {
return " " + brojevi_varijabla[0];
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result != null) Tbroj1.setText(result);
}
}

Categories

Resources