im working on this program ,which i have an Android app that uses Nodejs server.the host is -https://rocky-thicket-82184.herokuapp.com.
now, im trying to just send and recieve a post request . but it seems to not
work.
in the server side i get an error like : cannot GET/.
and in the client side i get :error exeption https://rocky-thicket-82184.herokuapp.com.
I cannot find the problem ,i feel like i'm missing something ...
here is my Android mainActivity.java:
package com.example.shanijoffe.hungry_monkey;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.JsonReader;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.os.AsyncTask;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.stormpath.sdk.Stormpath;
import com.stormpath.sdk.StormpathConfiguration;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.HttpResponse;
import cz.msebera.android.httpclient.NameValuePair;
import cz.msebera.android.httpclient.client.ClientProtocolException;
import cz.msebera.android.httpclient.client.HttpClient;
import cz.msebera.android.httpclient.client.entity.UrlEncodedFormEntity;
import cz.msebera.android.httpclient.client.methods.HttpPost;
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;
import cz.msebera.android.httpclient.message.BasicNameValuePair;
import static com.loopj.android.http.AsyncHttpClient.log;
public class MainActivity extends AppCompatActivity
{
EditText user_name_edit;
EditText password_edit;
Button loginButton;
String user;
String user_pass;
private static final String TAG = "MyActivity";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
user_name_edit=(EditText)findViewById(R.id.txt_usrname);
password_edit=(EditText)findViewById(R.id.txt_password);
loginButton=(Button)findViewById(R.id.btn_login);
Log.i(TAG,"before connection");
}
public void OnClick(final View view) {
view.setEnabled(false);
user=user_name_edit.getText().toString();
user_pass=password_edit.getText().toString();
new SendPostRequest().execute();
//
//
}
public class SendPostRequest extends AsyncTask<String, Void, String>
{
String user_name=user_name_edit.getText().toString();
String user_pass=password_edit.getText().toString();
protected void onPreExecute(){}
protected String doInBackground(String... arg0) {
try {
Log.e("MainActivity", "in SendPostRequest ");
URL url = new URL("https://rocky-thicket-82184.herokuapp.com");
InputStream inp = (InputStream) url.getContent();
Log.e("stream",inp.toString());
JSONObject postDataParams = new JSONObject();
postDataParams.put("username", user);
postDataParams.put("password", user_pass);
Log.e("params", postDataParams.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
int responseCode;
try (BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"))) {
String encoded_string = getPostDataString(postDataParams);
Log.e("encoded", encoded_string);
//writer.write(getPostDataString(postDataParams));
writer.write(postDataParams.toString());
writer.flush();
writer.close();
}
os.close();
responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
Log.i("MainActivty",sb.toString());
return sb.toString();
} else {
return new String("false : " + responseCode);
}
}
catch (Exception e)
{
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), result,
Toast.LENGTH_LONG).show();
}
public String getPostDataString(JSONObject params) throws Exception
{
StringBuilder result = new StringBuilder();
boolean first = true;
Iterator<String> itr = params.keys();
while(itr.hasNext()){
String key= itr.next();
Object value = params.get(key);
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(key, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value.toString(), "UTF-8"));
}
return result.toString();
}
}
}
and here is the nodejs code:
var express=require('express');
var bodyParser=require('body-parser');
var app=express();
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.get('/',function(req,res){
res.sendFile(__dirname + '/index.html');
});
app.post('/',function(req,res){
console.log(req.body);
if (!req.body)
return res.sendStatus(400)
res.send('welcome, ' + req.body.user)
});
app.listen(process.env.PORT || 3000)
can anyone take a look and see if they can help ?
Thanks alot :)
Related
I have many QR codes ex. Example on imgur, which has peoples' names, numbers, and emails, and I need to scan them. The data comes in something like this: "joe,1234567890,joe#joe.com". I want to write an app that uploads the data to a google sheet and I found a tutorial online from crazycodersclub.com, but when I do the same thing it gives me an error, something like:
Exception: Invalid argument: URL (line 11, file "Code")
Google Script Code
function doGet(e){
var url = encodeUrl("https://docs.google.com/spreadsheets/d/1IEAHcv2n33YO9d7IbfWNVLv2Hl1Q1UXveazPcgMZrMs/edit?usp=sharing/")
var ss = SpreadsheetApp.openByUrl(url);
var sheet = ss.getSheetByName("Sheet1");
return insert(e,sheet);
}
function doPost(e){
var url = encodeUrl("https://docs.google.com/spreadsheets/d/1IEAHcv2n33YO9d7IbfWNVLv2Hl1Q1UXveazPcgMZrMs/edit?usp=sharing/")
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1IEAHcv2n33YO9d7IbfWNVLv2Hl1Q1UXveazPcgMZrMs/edit?usp=sharing/");
var sheet = ss.getSheetByName("Sheet1");
return insert(e,sheet);
}
function insert(e,sheet) {
var scannedData = e.parameter.sdata;
var d = new Date();
var ctime = d.toLocaleString();
sheet.appendRow([scannedData,ctime]);
return ContentService
.createTextOutput("Success")
.setMimeType(ContentService.MimeType.JAVASCRIPT);
}
MainActivity.java
package com.tarbiya.scannerapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import javax.net.ssl.HttpsURLConnection;
public class MainActivity extends AppCompatActivity {
String scannedData;
Button scanBtn;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Activity activity =this;
scanBtn = (Button)findViewById(R.id.scan_btn);
scanBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
IntentIntegrator integrator = new IntentIntegrator(activity);
integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
integrator.setPrompt("Scan");
integrator.setBeepEnabled(false);
integrator.setCameraId(0);
integrator.setBarcodeImageEnabled(false);
integrator.initiateScan();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode,resultCode,data);
if(result!=null) {
scannedData = result.getContents();
if (scannedData != null) {
// Here we need to handle scanned data...
new SendRequest().execute();
}else {
}
}
super.onActivityResult(requestCode, resultCode, data);
}
public class SendRequest extends AsyncTask<String, Void, String> {
protected void onPreExecute(){}
protected String doInBackground(String... arg0) {
try{
//Enter script URL Here
URL url = new URL("https://script.google.com/macros/s/AKfycby_G_K-kmm77peQBSY6xmNZjsDcFIkDgqZwxz6e7guyte5Lxe8/exec");
JSONObject postDataParams = new JSONObject();
//int i;
//for(i=1;i<=70;i++)
// String usn = Integer.toString(i);
//Passing scanned code as parameter
postDataParams.put("sdata",scannedData);
Log.e("params",postDataParams.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line="";
while((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
}
else {
return new String("false : "+responseCode);
}
}
catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), result,
Toast.LENGTH_LONG).show();
}
}
public String getPostDataString(JSONObject params) throws Exception {
StringBuilder result = new StringBuilder();
boolean first = true;
Iterator<String> itr = params.keys();
while(itr.hasNext()){
String key= itr.next();
Object value = params.get(key);
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(key, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value.toString(), "UTF-8"));
}
return result.toString();
}
}
If you need to see more code, I can attach some more. It looks basically the same as the one in the tutorial right now.
Thank you so much for your help.
The reason you were receiving the Exception: Invalid argument: URL message is because the url you were passing to the openByUrl was not in the correct format.
If you check the documentation for the openByUrl method here, you can see the accepted format of the link.
https://docs.google.com/spreadsheets/d/abc1234567/edit
In your situation, you will have to remove the part after the /edit.
Reference
Apps Script SpreadsheetApp Class - openByUrl(url).
this is my class that receive data from server: it does not show notification
but if i take sendBroadcast(intent) and Intent out of try and catch blocks and make msg=null; it show notification but with empty message
please i need your help.
package com.example.hussienalrubaye.myapplication;
import android.app.IntentService;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class Sev_data extends IntentService {
public static boolean ServiceIsRun = false;
public Sev_data() {
super("MyWebRequestService");
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
while (ServiceIsRun) {
int id_s=0;//هنا رقم اخر رسلة وصلة التطبيق
String url0 = "http://localhost/sendapp.php?co>"+id_s;//رايط ملف الداتة من السيرفر
String msg;
try {
URL url = new URL(url0);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
msg = Stream2String(in);
in.close();
JSONObject jsonRootObject = new JSONObject(msg);
JSONArray jsonArray = jsonRootObject.optJSONArray("date");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String id= jsonObject.optString("id");
String title = jsonObject.optString("title");
String mess = jsonObject.optString("description");
///// هنا نهاية الموضوع دي اخر رسلة علي السيرفر
}
// creat new intent
intent = new Intent();
//set the action that will receive our broadcast
intent.setAction("com.example.Broadcast");
// add data to the bundle
intent.putExtra("msg", msg);
// send the data to broadcast
sendBroadcast(intent);
//delay for 50000ms
} catch (Exception e) {
}
try{
Thread.sleep(20000);
}catch (Exception ex){}
}
}
String date="";
public String Stream2String(InputStream inputStream) {
BufferedReader bureader=new BufferedReader( new InputStreamReader(inputStream));
String line ;
String Text="";
try{
while((line=bureader.readLine())!=null) {
Text+=line;
}
inputStream.close();
}catch (Exception ex){}
return Text;
}
}
and this is receiver class:
package com.example.doblist.mydobservice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// get the bundles in the message
final Bundle bundle = intent.getExtras();
// check the action equal to the action we fire in broadcast,
if ( intent.getAction().equalsIgnoreCase("com.example.Broadcast"))
//read the data from the intent
{ NewMessageNotification notfilyme= new NewMessageNotification();
notfilyme.notify(context,bundle.getString("msg"),223);}
// Toast.makeText(context,bundle.getString("msg"),Toast.LENGTH_LONG).show();
}
}
i add all AndroidManifest permission all things well but it dose not show notification
I want to know. is the cod that get data from server true or not
As title suggests, here is the format of the JSON:
http://prntscr.com/elb4fz. Now I'm not sure if I have the parse method working properly as I think that SearchResults is the array and it'll show each individual result as an object.
I have my networkutils code as such:
package companionsdirect.practice;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Albedo on 3/17/2017.
*/
public class NetworkingUtil {
private static final String TAG = "NetworkUtils";
List<Product> items = new ArrayList<>();
public byte[] getUrlBytes(String urlSpec) throws IOException {
URL url = new URL(urlSpec);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = connection.getInputStream();
if(connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new IOException(connection.getResponseMessage() +
": with " + urlSpec);
}
int bytesRead = 0;
byte[] buffer = new byte[1024];
while ((bytesRead = in.read(buffer)) > 0) {
out.write(buffer, 0, bytesRead);
}
out.close();
return out.toByteArray();
} finally {
connection.disconnect();
}
}
public String getUrlString(String urlSpec) throws IOException {
return new String(getUrlBytes(urlSpec));
}
public List<Product> fetchItems(String url) {
try {
String jsonString = getUrlString(url);
Log.i(TAG, "Received JSON: " + jsonString);
JSONObject jsonBody = new JSONObject(jsonString);
parseItems(items, jsonBody);
} catch (IOException ioe) {
Log.i(TAG, "Failed to fetch items", ioe);
} catch (JSONException je) {
Log.e(TAG, "Failed to parse JSON", je);
}
return items;
}
public List<Product> getProdList() {
return items;
}
private void parseItems(List<Product> items, JSONObject jsonBody) throws IOException, JSONException {
//JSONObject reviewItem = jsonBody.getJSONObject();
JSONArray reviewArray = jsonBody.getJSONArray("SearchResults");
for(int i = 0;i<reviewArray.length();i++) {
JSONObject reviewItem = reviewArray.getJSONObject(i);
Product currentProductReview = new Product();
currentProductReview.setmSummary(reviewItem.getString("Summary"));
currentProductReview.setmTitle(reviewItem.getString("Title"));
currentProductReview.setmRecordType(reviewItem.getString("RecordType"));
items.add(currentProductReview);
}
}
}
And this is the activity with the asynctask:
package companionsdirect.practice;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class ReturnReviewsActivity extends AppCompatActivity {
public String builtURL;
List<Product> prodList;
private static final String TAG = "ReturnReviewsActivity";
private TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_return_reviews);
Intent intent = getIntent();
String url = intent.getStringExtra(MainActivity.EXTRA_MSG);
prodList = new ArrayList<Product>();
builtURL = url;
new FetchItemsTask().execute();
tv = (TextView) findViewById(R.id.tv);
for(Product x : prodList) {
tv.setText(x.getmTitle() + " " + x.getRating() + " \n");
}
}
private class FetchItemsTask extends AsyncTask<Void, Void, Void> {
private List<Product> list;
#Override
protected Void doInBackground(Void... params) {
NetworkingUtil productData = new NetworkingUtil();
list = productData.fetchItems(builtURL);
return null;
}
}
}
What gives? The log shows that the json is being received,but I try to set the textview to whatever is in the list and nothing shows.
Try this
tv = (TextView) findViewById(R.id.tv);
for(Product x : prodList) {
//append the text view
tv.append(x.getmTitle() + " " + x.getRating() + " \n");
}
restful service in android authenticating and connecting it to the url
new to android
unable to get the output : username password and connecting to the url
package com.example.newrestapi;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText password,userName;
Button login;
ProgressBar progressBar;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
password=(EditText) findViewById(R.id.editText2);
userName=(EditText) findViewById(R.id.editText1);
login=(Button) findViewById(R.id.button1);
//progess_msz.setVisibility(View.GONE);
progressBar=(ProgressBar) findViewById(R.id.progressBar1);
progressBar.setVisibility(View.GONE);
login.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
progressBar.setVisibility(View.VISIBLE);
String s1=userName.getText().toString();
String s2=password.getText().toString();
new ExecuteTask().execute(s1,s2);
}
});
}
class ExecuteTask extends AsyncTask<String, Integer, String>
{
#Override
protected String doInBackground(String... params) {
String res=PostData(params);
return res;
}
#Override
protected void onPostExecute(String result) {
progressBar.setVisibility(View.GONE);
//progess_msz.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), result, 50000).show();
}
}
public String PostData(String[] values) {
String s="";
try
{
HttpClient httpClient=new DefaultHttpClient();
HttpGet httpGet=new HttpGet("http://myrul");
HttpResponse httpResponse= httpClient.execute(httpGet);
HttpEntity httpEntity=httpResponse.getEntity();
s= readResponse(httpResponse);
}
catch(Exception exception) {}
return s;
}
public String readResponse(HttpResponse res) {
InputStream is=null;
String return_text="";
try {
is=res.getEntity().getContent();
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(is));
String line="";
StringBuffer sb=new StringBuffer();
while ((line=bufferedReader.readLine())!=null)
{
sb.append(line);
}
return_text=sb.toString();
} catch (Exception e)
{
}
return return_text;
}
}
login authentication using android restful services
So I am trying to create an Android app which basically reads out the twitter feed according to the search query inside a UI. The feed that I need to display form the parsed JSON is the user name, handle, profile picture and the tweet.
Now I have created the whole thing and my code compiles but as soon as I run it the app opens and I write something in the search feed and hit enter - " Unfortunately, AppName has stopped working " I am attaching my logcat and my source code for reference.
*Solved the issue by removing set text from DoInBackground and then giving adequate permission for Android to access internet. The issue now is that as I try and display the profile picture, the URL gets displayed, not the image.
Source code :
package com.example.twittersearchactivity;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class TwitterSearchActivity extends Activity {
private TextView tweetDisplay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_twitter_search);
tweetDisplay = (TextView)findViewById(R.id.tweet_txt);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.twitter_search, menu);
return true;
}
public void searchTwitter(View view){
EditText searchTxt = (EditText)findViewById(R.id.search_edit);
String searchTerm = searchTxt.getText().toString();
if(searchTerm.length()>0){
try{
String encodedSearch = URLEncoder.encode(searchTerm, "UTF-8");
String searchURL = "http://search.twitter.com/search.json?q="+encodedSearch;
new GetTweets().execute(searchURL);
Log.i("1", "entered the searchterm");
}
catch(Exception e){
tweetDisplay.setText("Whoops - something went wrong!");
e.printStackTrace();
}
}
else
tweetDisplay.setText("Enter a search query!");
}
private class GetTweets extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... twitterURL) {
StringBuilder tweetFeedBuilder = new StringBuilder();
for (String searchURL : twitterURL) {
HttpClient tweetClient = new DefaultHttpClient();
try {
HttpGet tweetGet = new HttpGet(searchURL);
HttpResponse tweetResponse = tweetClient.execute(tweetGet);
StatusLine searchStatus = tweetResponse.getStatusLine();
if (searchStatus.getStatusCode() == 200) {
HttpEntity tweetEntity = tweetResponse.getEntity();
Log.i("2", "entered gettweets");
InputStream tweetContent = tweetEntity.getContent();
InputStreamReader tweetInput = new InputStreamReader(tweetContent);
BufferedReader tweetReader = new BufferedReader(tweetInput);
String lineIn;
while ((lineIn = tweetReader.readLine()) != null) {
tweetFeedBuilder.append(lineIn);
Log.i("3", "entered while in dobackground");
}
}
else {Log.i("error", "error");}
//tweetDisplay.setText("Whoops - something went wrong!");
}
catch(Exception e) {
Log.e("DEBUGTAG", "Remote Image Exception", e);
//tweetDisplay.setText("Whoops - something went wrong!");
e.printStackTrace();
}}
return tweetFeedBuilder.toString();
}
protected void onPostExecute(String result) {
StringBuilder y;
StringBuilder tweetResultBuilder = new StringBuilder();
try {
Log.i("tag", "entered try block");
JSONObject resultObject = new JSONObject(result);
JSONArray tweetArray = resultObject.getJSONArray("results");
for (int t=0; t<tweetArray.length(); t++) {
Log.i("tag", "entered the json stream");
JSONObject tweetObject = tweetArray.getJSONObject(t);
tweetResultBuilder.append(tweetObject.getString("from_user")+": ");
tweetResultBuilder.append(tweetObject.getString("from_user_name")+": ");
tweetResultBuilder.append(tweetObject.get("text")+"\n\n");
String imageURL = (String) tweetObject.get(("profile_image_url")+": ");
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageURL).getContent());
#SuppressWarnings("deprecation")
Drawable d =new BitmapDrawable(bitmap);
d.setAlpha(255);
TextView.setCompoundDrawablesWithIntrinsicBounds(0,0,1,0);
}
}
catch (Exception e) {
tweetDisplay.setText("Whoops - something went wrong!");
e.printStackTrace();}
if(tweetResultBuilder.length()>0)
tweetDisplay.setText(tweetResultBuilder.toString());
else
tweetDisplay.setText("Sorry - no tweets found for your search!");
}
}}
You can't call view functions like setText on another thread like an AsyncTask doInBackground function. You need to do it in onPostExecute.