i am trying to send a notifications from the on progressupdate method from the asynctack class. Since i am a newbie to android, i don't know where seem to be the error. The AllSensorData is a separate java clas. It would be great if you could help. thanks
Here's my code for the asyntack class
public class AllSensorData extends AsyncTask<String, byte[], String>{
TextView temp,humi,motion,smoke,flame,water,reed,data;
int notificationID = 1;
NotificationManager notificationManager =null;
Context context;
public AllSensorData(TextView temp,TextView humi,TextView motion,TextView smoke,TextView flame,TextView water,TextView reed) {
this.temp=temp;
this.humi=humi;
this.motion=motion;
this.smoke=smoke;
this.flame=flame;
this.water=water;
this.reed=reed;
}
InputStream nis;
OutputStream nos;
BufferedReader in;
DefaultHttpClient httpclient =new DefaultHttpClient();
URL url;
URLConnection urlconn=null;
InputStreamReader isn;
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
try {
while(true){//while connected
HttpGet httpget =new HttpGet("http://192.168.1.177/");
response = httpclient.execute(httpget);
in=new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String msgFromServer = in.readLine();//read the lines coming from the socket
byte[] theByteArray = msgFromServer.getBytes();//store the bytes in an array
publishProgress(theByteArray);//update the publishProgress
if(isCancelled()){
break;
}
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return null;
}
protected void onProgressUpdate(byte[]... values) {
super.onProgressUpdate(values);
String command=new String(values[0]);//get the String from the recieved bytes
String[] parts= command.split(",");
String part1=parts[0];
String part2=parts[1];
temp.setText(part1);
humi.setText(part2);
if(Integer.parseInt(part2)>70)
{
NotificationCompat.Builder builder=new NotificationCompat.Builder(this.context);
builder.setContentTitle("AM Home Automation");
builder.setContentText("humidity > 70");
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setTicker("alert");
builder.setDefaults(Notification.DEFAULT_ALL);
//builder.setSound(Uri.parse("android.resource://"+getPackageName()+"/"+R));
notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notificationID, builder.build());
notificationID++;
}
}
}
as i was going through the code, I dont think that context is initialized properly although it has been declared in the class. Could you cross check that it has beeen initialized before it is used anywhere in the class ( specially in notification builder)
try making the following change in the class
public AllSensorData(TextView temp,TextView humi,TextView motion,TextView smoke,TextView flame,TextView water,TextView reed, Context context) {
this.temp=temp;
this.humi=humi;
this.motion=motion;
this.smoke=smoke;
this.flame=flame;
this.water=water;
this.reed=reed;
this.context=context
}
Also, remember to pass application context when you initialize this class as follows from your main activity:
AllSensorData mSensorData = new AllSensorData(temp, humi, motion, smoke, flame, water,reed,getApplicationContext());
That might just solve your problem!
Related
Background:
I am new to android programming. I want to simply do an http get request to a local server.
I want to pass this request a name as a parameter and want to get a return in json. This issue that I cannot execute it on the main thread. How can I do this?
Here is what I tried:
main class:
itemsAdapter.add(get.getName(device.getName()));
Seperate class in same file:
private class httpGet extends AsyncTask<Editable, Void, Integer> {
protected String doInBackground(Editable... params) {
Editable editable = params[0];
return getName(editable.toString());
}
final String getName(String btName) {
HttpResponse response = null;
String result = "";
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
URI website = new URI("http://192.168.1.105/getName.php?q=" + btName);
request.setURI(website);
response = client.execute(request);
// Convert String to json object
JSONObject json = new JSONObject(response.toString());
// get LL json object
JSONObject json_Name = json.getJSONObject("Name");
// get value from LL Json Object
name = json_Name.getString("value"); //<< get value here
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
// Do something to recover ... or kill the app.
}
return result;
}
protected void onPostExecute(Integer result) {
// here you have the result
}
I am not sure if this is even a good way to do this task. I also have no idea how I would call it.
AsyncTask allows you to perform a background operation in a different thread without manipulating threads/handlers.
It should be this way:
private class httpGet extends AsyncTask<ParamForDoInBackground, ParamForOnProgressUpdate, ParamForOnPostExecute> {
protected Long doInBackground(ParamForDoInBackground... urls) {
// do the request here
}
protected void onProgressUpdate(ParamForOnProgressUpdate progress) {
// if you need to show any progress of the
// request from doInBackground
}
protected void onPostExecute(ParamForOnPostExecute result) {
// this method will run when doInBackground
// is done executing
}
}
Then you can execute an AsyncTask:
new httpGet().execute(ParamForDoInBackground);
You can use the following as a reference: AndroidBackgroundProcessing and Android Developer AsyncTask
You should learn how the asyncTask work. Inside DoInBackground you should to put the code referent to the HTTPRequest. I recommend to use methods to improve the understanding of code. Here is an example of one of my apps:
public String query(String uri) {
HttpClient cliente = new DefaultHttpClient();
HttpContext contexto = new BasicHttpContext();
HttpPost httpPost = new HttpPost(uri);
HttpResponse response = null;
String resultado=null;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("dato", cod_restaurante));
httpPost.setEntity(new UrlEncodedFormEntity(params));
response = cliente.execute(httpPost, contexto);
HttpEntity entity = response.getEntity();
resultado = EntityUtils.toString(entity, "UTF-8");
} catch (Exception e) {
// TODO: handle exception
}
return resultado;
}
private class MyAsyncTask extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params)
{
result=query(params[0]);
return result;
}
protected void onPostExecute(final String resultadoDoInBackground)
{
//here put the code to modify the UI
}
}
Then in your activity onCreate() method you execute the Asynktask.
new MyAsyncTask().execute(" ");
You can read more about AsyncTask here:
AsyncTask Android Developer
I am totally new in java and android.. I am sure I did it wrong on the code, please help me fix it
I try to send the content of a tweet as a String from an android application to this online parser: http://demo.ark.cs.cmu.edu/parse, and I want to retrieve the result of the parsing, here is my code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
String Tobetag = urlEncode(contentTweet);
new Analyser().execute();
}
private String urlEncode(String s){
try {
return URLEncoder.encode(s,"UTF-8").replace("+", "%20");
}
catch ( UnsupportedEncodingException e) {
throw new RuntimeException(s,e);
}
}
private class Analyser extends AsyncTask<Integer, Integer, Integer>
{
private String mUrl = "http://demo.ark.cs.cmu.edu/parse?sentence=";
#Override
protected Integer doInBackground(Integer... params) {
// TODO Auto-generated method stub
try
{
DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(mUrl + mTobetag));
HttpResponse response = client.execute(request);
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader( new InputStreamReader(in) );
String result = reader.readLine();
System.out.println("Top");
System.out.println(result);
System.out.println("Bottom");
in.close();
}
catch(Exception e)
{
Log.e("Twitter", "doInBackground_" + e.toString());
}
return new Integer(1);
}
protected void onProgressUpdate(Integer... progress) {
}
#Override
protected void onPostExecute(Integer i) {
}
}
I ran the code, no error reported but I didn't get the parse result, I only have this:
What can I do to get the result I wanted?
P.S. Also I am not sure I used the urlencoder right, it turn the slashes of the tweet content into %2F, but when I use the online parser by a browser, it shows that it doesn't change the slashed at all, please help
You are reading only the first line of the response, if you want to read the entire response you can do it like this:
String result = "";
for(String line;(line=br.readLine())!=null;){
result += line;
}
This will get you the entire http://demo.ark.cs.cmu.edu/parse page as a response, if you want the response to be only a JSON object, use this URL instead http://demo.ark.cs.cmu.edu/parse/api/v1/parse?sentence=....
I'm trying to get data through web services, So that I'm using below shown asynctask calls. It gives me a null point exception as shown in the below screen shot. What can be the issue?
Activity class
new PickupAsyncTask(getApplicationContext(), null).execute();
Asynctask class
public class PickupAsyncTask extends AsyncTask<String, Integer, JSONArray> {
private OnTaskCompleted listener;
private JSONArray responseJson = null;
private Context contxt;
private Activity activity;
public PickupAsyncTask(Context context, OnTaskCompleted listener) {
// API = apiURL;
this.contxt = context;
this.listener = listener;
}
// async task to accept string array from context array
#Override
protected JSONArray doInBackground(String... params) {
String path = null;
String response = null;
HashMap<String, String> request = null;
JSONObject requestJson = null;
DefaultHttpClient httpClient = null;
HttpPost httpPost = null;
StringEntity requestString = null;
ResponseHandler<String> responseHandler = null;
try {
path = "http://xxxxxxxxxxxxxxx/LocationService.svc/StreetDetails";
new URL(path);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
// set the API request
request = new HashMap<String, String>();
request.entrySet().iterator();
// Store locations in JSON
requestJson = new JSONObject(request);
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(path);
requestString = new StringEntity(requestJson.toString());
// sets the post request as the resulting string
httpPost.setEntity(requestString);
httpPost.setHeader("Content-type", "application/json");
// Handles the response
responseHandler = new BasicResponseHandler();
response = httpClient.execute(httpPost, responseHandler);
responseJson = new JSONArray(response);
System.out.println("*****JARRAY*****" + responseJson.length());
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return responseJson;
}
#Override
protected void onPostExecute(JSONArray result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
listener.onTaskCompleted(responseJson); //line 101
}
}
OnTaskCompleted.java
public interface OnTaskCompleted {
void onTaskCompleted(JSONArray responseJson);
}
listener is null. Introduce a check to verify that listener is not null before calling any methods on it.
Edit
If you want to handle the task completion, pass an anonymous object of OnTaskCompleted to PickupAsyncTask constructor as follows:
new PickupAsyncTask(context, new OnTaskCompleted() {
#Override
public void onTaskCompleted(JsonArray response) {
//Handle the task completion
}
}).execute();
I am making an app that will download a string from a website and display it.
I tried many examples online and I've literally been searching for days for this, but I can't find a single solution.
From what I have read, I know I have to get the content of the url from another thread, but no tutorial showed me how to do this.
I have a textview on the layout and that will be where the html content will have to show up.
Can anybody show me an example of how this is done?
What about something like this?
public class MyAsyncTask extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... requestUrl)
{
String result = null;
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(requestUrl[0]);
try
{
ResponseHandler<String> responseHandler = new BasicResponseHandler();
result = httpClient.execute(request, responseHandler);
}
catch (IOException e)
{
Log.e("requestStringFromWebServer", "Whoops!", e);
}
httpClient.getConnectionManager().shutdown();
return result;
}
#Override
protected void onPostExecute(String result)
{
if (result != null)
{
// Handle the result from your request here...
}
}
}
And kick it off with
String myUrlStr; // Initialize this to your url
new MyAsyncTask().execute(myUrlStr);
I am trying to access the android network by starting a TCP server. But when I create a new thread, either by
Thread t = new Thread(runnable);
t.start();
or FutureTask I still get the networkonmainthreadexception...
Use AsyncTask to perform network related ops
For Example :
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
textView.setText(result);
}
}
Or you can do this, Although it is not recommended
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
adding this code will not give you network on main thread exception anymore.
You have to do the actual network IO on the run() function of the runnable in the thread. You don't just create a thread and then do the IO.