I'm trying to print The destination addresses & their distances from the origin in the textView. However, I keep getting error or just show the last value. I don't want the text view get updated, I want the new value to be printed under the new one
Here is my code
public class MainActivity extends Activity {
private static final String TAG_ROWS = "rows";
private static final String TAG_ELEMENTS = "elements";
private static final String TAG_DISTANCE = "distance";
private static final String TAG_VALUE = "value";
private static final String TAG_ADDRESS = "destination_addresses";
String Addresses[]= {"2906+west+Broadway+Vancouver+BC","4750+Kingsway+Burnaby+BC","2633+Sweden+Way+110+Richmond","943+Marine+Dr+North+Vancouver","4567+Lougheed+Hwy+Burnaby"};
String data;
HttpClient client;
double minDistance=0;
static JSONObject jObj = null;
String destination_addresses;
JSONArray rows;
String destination;
String distanceStr;
String[] value_destination;
String value;
final static String URL= "http://maps.googleapis.com/maps/api/distancematrix/json?";
TextView result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView) findViewById(R.id.text1);
result.setText("Distace from the location" + destination + " is :" + distanceStr );
new TestGoogleMaps().execute("");
}
public class TestGoogleMaps extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
try {
ClosestObject();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
finally {
}
return null;
}
#Override
protected void onPostExecute(String resuls) {
// TODO Auto-generated method stub
super.onPostExecute(resuls);
}
}
public void ClosestObject() throws JSONException, ClientProtocolException, IOException {
// Creating JSON Parser instance
StringBuilder url = new StringBuilder(URL);
client=new DefaultHttpClient();
for (int index=0; index<Addresses.length; index++){
String str_parameters = "origins="+ URLEncoder.encode("1359+Richards+Street+Vancouver+BC","UTF-8")+"&destinations="+ URLEncoder.encode(Addresses[index],"UTF-8")+"&mode=driving&language="+ URLEncoder.encode("en-FR","UTF-8")+"&sensor=false";
System.out.println("URL URl :: "+url+str_parameters);
HttpGet get = new HttpGet(url+str_parameters);
get.setHeader("Accept", "application/json");
get.setHeader("Content-type", "application/json");
HttpResponse r = client.execute(get);
HttpEntity en = r.getEntity();
data = EntityUtils.toString(en);
System.out.println("ClosestObject Response :: "+data);
try {
jObj = new JSONObject(data);
destination = jObj.getString("destination_addresses");
// printing the destination and checking wheather parsed correctly
Log.v("Destination", destination);
JSONArray jarRow = jObj.getJSONArray("rows");
for(int i=0;i<jarRow.length(); i++){
// creating an object first
JSONObject ElementsObj = jarRow.getJSONObject(i);
// and getting the array out of the object
JSONArray jarElements = ElementsObj.getJSONArray("elements");
for(int j=0; j<jarElements.length(); j++){
JSONObject distanceObj = jarElements.getJSONObject(j).getJSONObject("distance");
distanceStr = distanceObj.getString("value");
Log.v("finally getting distance : ", distanceStr);
} }
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
How can I print all the members on my TextView?
I want the new value to be printed under the new one
So if you want to print your all destinations into TextView most efficient way will be to use for example StringBuffer to create whole String that will be finally assigned to your TextView.
I recommend you change your return type of ClosestObject method to StringBuffer(or Builder) and in your loop append data to it. Also change third parameter of AsyncTask to StringBuffer.
Pseudo-code:
#Override
protected StringBuffer doInBackround() {
...
StringBuffer buff = ClosestObject();
return buff;
}
In your ClosestObject method:
StringBuffer buff = new StringBuffer();
for (int i = 0; i < arr.length(); i++) {
// getting values from JSON
buff.append(value).append("\n"); // buff.append(value1 + "," + value2 + "\n")
}
...
return buff;
and finally update your TextView from onPostExecute() method that already runs on UI Thread and allows updates.
yourTextView.setText(result.toString());
Note:
Don't forget that by naming conventions in Java, method's signature should start with lowercase letter and not with uppercase.
Try this:
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
result.setText(result.getText().toString() + "\n" + distanceStr);
}
});
You must update the TextView on the UI Thread as shown because the JSON response is received in a different Thread from your AsyncTask, otherwise you will receive a CalledFromTheWrongThreadException.
Related
Sooo here is my OnCreateView code
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_profile, container, false);
tvMemberName = (TextView) v.findViewById(R.id.member_name);
UrlPostHelper uph = new UrlPostHelper();
uph.execute();
return v;
}
and AsyncTask
private class UrlPostHelper extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
String url = "http://localhost:8080/MP/Profile";
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response;
String data = "no response";
try {
response = httpClient.execute(httpGet);
data = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String s = "yow";
try {
JSONArray ja = new JSONArray(data);
for (int i = 0 ; i < ja.length(); i++ ){
JSONObject j = ja.getJSONObject(i);
String firstName = j.getString("firstName");
String lastName = j.getString("lastName");
System.out.println(firstName);
s = firstName +" " + lastName;
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return s;
}
protected void onPostExecute(String result){
super.onPostExecute(result);
Log.i("TAG", result );
tvMemberName.setText(result);
}
}
My problem is that in my android app it does not show anything at first but after a while like around 1-2 minutes the "yow" will show. It is not replaced with the member name though. I tried running my servlet and it works just fine. Please help me.
AsyncTask<Params, Progress, Result>.
private class UrlPostHelper extends AsyncTask<Void, Void, String>{
private EditText tvMemberName;
public UrlPostHelper(EditText tv){
this.tvMemberName = tv;
}
Return Text after background task finished.
#Override
protected String doInBackground(Void... params) {
HttpResponse response;
String data = "no response";
try {
response = httpClient.execute(httpGet);
data = getJSONString(response.getEntity());
} catch (Exception e) {
e.printStackTrace();
}
return data; //Text to set TvMember Value
}
Get String from response Util.
public String getJSONString(InputStream is) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
Set EditText onPostExecute.
protected void onPostExecute(String result){
Log.i("TAG", result );
tvMemberName.setText(result);
}
Pass EditText with the UrlPostHelper call.
new UrlPostHelper(tvMemberName).excute();
public class DetailsActivity extends Activity {
private ArrayAdapter<Imageclass> adapter;
ArrayList<String> imageselect = new ArrayList<String>();
private ArrayList<Imageclass> array1;
private ArrayList<Imageclass> list = new ArrayList<Imageclass>();
//private ArrayList<Imageclass> array;
ArrayList<String> imagetest = new ArrayList<String>();
private TextView textView1;
private TextView textView2;
private TextView textView3;
private TextView textView4;
private TextView textView5;
int id;
int pid;
int val;
int val_new;
double lati;
double longi;
String imagename;
//private ImageView image;
//public static final String URL = "http://theopentutorials.com/totwp331/wp-content/uploads/totlogo.png";
ImageView image;
static Bitmap bm;
ProgressDialog pd;
BitmapFactory.Options bmOptions;
public class test extends AsyncTask<Void, Void, InputStream>{
ArrayList<Imageclass> str;
private DetailsActivity activity;
public test(DetailsActivity activity){
this.activity = activity;
}
#Override
protected InputStream doInBackground(Void... params) {
//String stringURL = "http://192.168.2.104:8088/Image/MyImage" + String.format("?id=%d",id);
Log.e("Checking id",""+id);
String stringURL = "http://megavenues.org/mobile_json/get_images" + String.format("?id=%d",id);
URL url;
try {
stringURL=stringURL.replaceAll(" ", "%20");
url = new URL(stringURL);
Log.e("URL",""+ url);
URLConnection conn= url.openConnection();
Log.e("URLConnection",""+conn );
InputStream stream= conn.getInputStream();
Log.e("URLStream",""+stream );
return stream;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
Log.e("Excepiton", ""+e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(InputStream result) {
super.onPostExecute(result);
Log.e("Result", ""+result);
StringBuilder builder = new StringBuilder();
Log.e("Builder", ""+ builder);
BufferedReader reader = new BufferedReader(new InputStreamReader(result));
Log.e("Reader", ""+ reader);
String line = null;
try {
while((line = reader.readLine()) != null) {
Log.e("Result11", ""+ builder.append(line));
builder.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
String jsonString = builder.toString();
Log.e("image", jsonString);
try {
JSONObject rootObject = new JSONObject(jsonString);
Log.e("JSOnObject",""+ rootObject);
JSONArray jsonArray = rootObject.getJSONArray("tbl_ads_images");
//array1.clear();
ArrayList<String> imagearray = new ArrayList<String>();
for (int index = 0; index < jsonArray.length(); index++) {
Imageclass imageinstance = new Imageclass();
JSONObject object = (JSONObject) jsonArray.get(index);
Log.e("Image test", "" + object);
imageinstance.image = object.getString("file_name");
//### this contain the image name
Log.e("Imageinstance.image",""+imageinstance.image);
imagename = imageinstance.image;
imagearray.add(imageinstance.image);
array1.add(imageinstance);
//array1.add(imagearray);
Log.e("array1","test"+array1);
}
Log.e("IMAGES",""+array1);
activity.setlist(array1);
}
catch (JSONException e) {
Log.e("this Exception",""+ e);
e.printStackTrace();
}
catch (Exception e) {
Log.e("NULL","NULL"+e);
}
// adapter.notifyDataSetChanged();
}
}
public class ImageDownload extends AsyncTask<String, Void, String> {
protected String doInBackground(String... param) {
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
String imageUrl ="http://megavenues.com/assets/uploads/users/"+val+"/ads/thumbnail/"+Finalname;
Log.e("inside img",""+Finalname);
Log.e("inside img_val",""+val);
Log.e("Check","check"+imageUrl);
loadBitmap(imageUrl, bmOptions);
return imageUrl;
}
protected void onPostExecute(String imageUrl) {
pd.dismiss();
if (!imageUrl.equals("")) {
Log.e("Test","Test"+ imageUrl.equals(""));
image.setImageBitmap(bm);
} else {
Toast.makeText(DetailsActivity.this,
"test", Toast.LENGTH_LONG)
.show();
}
}
}
public static Bitmap loadBitmap(String URL, BitmapFactory.Options options) {
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bm = BitmapFactory.decodeStream(in, null, options);
in.close();
} catch (IOException e1) {
}
return bm;
}
private static InputStream OpenHttpConnection(String strURL)
throws IOException {
InputStream inputStream = null;
URL url = new URL(strURL);
URLConnection conn = url.openConnection();
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
} catch (Exception ex) {
}
return inputStream;
}
String Finalname;
//String imageUrl ="http://megavenues.com/assets/uploads/users/220/ads/thumbnail/"+Finalname;
public void setlist(ArrayList<Imageclass> list)
{
this.list= list;
Log.e("LIST",""+ this.list);
String imagename1 = list.toString();
Log.e("image new value",""+imagename1);
this.list= list;
Log.e("testing",""+ this.list);
for (int i=0; i < list.size(); i++)
{
Log.e("new check",""+list.get(i));
//String test2= list.get(i).toString();
imagetest.add(list.get(i).toString());
Finalname = list.get(i).toString();
getimage_name(Finalname);
Log.e("Come",""+list.get(i).toString());
Log.e("Finalname",""+Finalname);
}
}
//String imageUrl ="http://megavenues.com/assets/uploads/users/"+val+"/ads/thumbnail/"+Finalname;
private void getimage_name(String finalname2) {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
image = (ImageView)findViewById(R.id.imageView2);
// getMenuInflater().inflate(R.menu.details);
//R.id.textDetailPlace
textView1 = (TextView)findViewById(R.id.textDetailPlace);
textView2 = (TextView)findViewById(R.id.textDetailAddress );
textView3 = (TextView)findViewById(R.id.textCapacity);
// textView4 = (TextView)findViewById(R.id.textDetailContactNo);
textView5 = (TextView) findViewById(R.id.textViewDescription);
textView1.setText(getIntent().getExtras().getString("test"));
textView2.setText(getIntent().getExtras().getString("test2"));
textView3.setText(getIntent().getExtras().getString("test3"));
//textView4.setText(getIntent().getExtras().getString("test4"));
textView5.setText(getIntent().getExtras().getString("test5"));
id = getIntent().getExtras().getInt("test6");
Log.e("ID value",""+id);
pid = getIntent().getExtras().getInt("test7");
Log.e("PID value",""+pid);
lati = getIntent().getExtras().getDouble("testlat");
Log.e("long",""+lati);
longi = getIntent().getExtras().getDouble("testlong");
Log.e("long",""+longi);
val=pid;
Log.e("val",""+val);
ActionBar actionBar = getActionBar();
actionBar.hide();
pd = ProgressDialog.show(DetailsActivity.this, null, null,true);
pd.setContentView(R.layout.progress);
array1 = new ArrayList<Imageclass>();
//new test(this).execute();
new test(this).execute();
here test asynctask is called
Log.e("JUST","CHECK");
Log.e("JUST","CHECK");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
here imageDownload asynctask is getting called::
new ImageDownload().execute();
Log.e("imagename",""+imagename);
}
}
here before ImageDownload is start executing before test async task is complete
and i am not able to get the status of the task can u tell how it is done
whatever i understood from this you want to execute your ImageDownload thread after the task thread,so start the ImageDownload Thread from the onPostExecute() of your task thread
When executing an async task a new thread is started, but your current thread keeps running. It immediately runs into your thread.sleep(1000) just after starting test.async.
It looks like your doing some internet downloading in test.async, and as you might have guessed, it takes longer than 1000 milliseconds (1 second). This means 1 second later, your other async is starting, before the first completed.
I assume you want to stagger them. In the postExecute of the first async, you can spawn the second async. A more stylistically correct method would be to implement an interface on your activity that takes a callback on Async completion, then upon receiving the call back, launch your second async.
An example of how to structure this is below.
interface AsyncCallback{
void onAsyncComplete();
}
public class ExampleActivity extends Activity implements AsyncCallback {
....
public void launchFirstAsync(){
new Task(this).execute();
}
#Override
public void onAsyncComplete() {
//todo launch second asyncTask;
}
}
class Task extends AsyncTask<Void, Void, Void>{
AsyncCallback cb;
Task(AsyncCallback cb){
this.cb = cb;
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
cb.onAsyncComplete();
}
}
Have a look here, This Help me for same..Pass your url to GetTemplateImageController and get the result in Bitmap array
GetTemplateImageController Class:
public class GetTemplateImageController extends AsyncTask<String, Void, Bitmap[]>
{
Context mcontext;
private ProgressDialog pDialog;
public static String[] imageurls;
public static Bitmap bm[]=new Bitmap[15];
// URL to get JSON
private static final String url= "http://xxx.xxx.xxx.xxx/image_master.php?";
private static final String TEMPLATE = "Template_images";
private static final String IMAGEURLS = "tempimagename";
// JSONArray
JSONArray loginjsonarray=null;
//result from url
public GetTemplateImageController(Context c) {
this.mcontext=c;
}
protected void onPreExecute() {
// Showing progress dialog
super.onPreExecute();
pDialog=new ProgressDialog(mcontext);
pDialog.setMessage("Loading");
pDialog.setCancelable(true);
pDialog.setIndeterminate(true);
pDialog.show();
}
protected Bitmap[] doInBackground(String... arg) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("templateMasterId",arg[0].toString()));
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonstr = sh.makeServiceCall(url, ServiceHandler.POST, params);
Log.d("Response: ", ">"+jsonstr);
if(jsonstr!=null)
{
try {
JSONObject jsonObj =new JSONObject(jsonstr);
loginjsonarray=jsonObj.getJSONArray(TEMPLATE);
imageurls=new String[loginjsonarray.length()];
for(int i=0;i<loginjsonarray.length();i++)
{
JSONObject l=loginjsonarray.getJSONObject(i);
imageurls[i]=l.getString(IMAGEURLS);
}
for(int i=0;i<imageurls.length;i++){
bm[i]=DownloadImage(imageurls[i]);
}
}catch(JSONException e){
e.printStackTrace();
}
}else{
Toast.makeText(mcontext,"Check your Internet Connection",Toast.LENGTH_SHORT).show();
}
return bm;
}
public Bitmap DownloadImage(String STRURL) {
Bitmap bitmap = null;
InputStream in = null;
try {
int response = -1;
URL url = new URL(STRURL);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
}catch(Exception ex) {
throw new IOException("Error connecting");
}
bitmap = BitmapFactory.decodeStream(in);
in.close();
}catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Integer result) {
// Dismiss the progress dialog
pDialog.dismiss();
if(result != null)
Toast.makeText(mcontext,"Download complete", Toast.LENGTH_SHORT).show();
//}
}
}
ServiceHandler Class:
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method, List<NameValuePair> params) {
try {
DefaultHttpClient httpClient=new DefaultHttpClient();
HttpEntity httpEntity=null;
HttpResponse httpResponse=null;
// Checking http request method type
if(method==POST){
HttpPost httpPost=new HttpPost(url);
if(params!=null)
{
//adding post params
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse=httpClient.execute(httpPost);
}
else if(method==GET)
{
// appending params to url
if(params!=null)
{
String paramString=URLEncodedUtils.format(params, "utf-8");
url +="?"+paramString;
}
HttpGet httpGet=new HttpGet(url);
httpResponse=httpClient.execute(httpGet);
}
httpEntity=httpResponse.getEntity();
response=EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}
}
Over time there have been several changes to the way Android deals with AsyncTasks that run concurrently. In very old Android versions (pre-1.6 afaik) multiple AsyncTasks were executed in sequence. That behavior has been changed to run the AsyncTasks in parallel up until Android 2.3. Beginning with Android 3.0 the the Android team decided that people were not careful enough with synchronizing the tasks that run in parallel and switched the default behavior back to sequential execution. Internally the AsyncTask uses an ExecutionService that can be configured to run in sequence (default) or in parallel as required:
ImageLoader imageLoader = new ImageLoader( imageView );
imageLoader.executeOnExecutor( AsyncTask.THREAD_POOL_EXECUTOR, "http://url.com/image.png" );
I am creating an Online Dictionary Android App.
I am using JSON to request for definitions for a word which the user inputs.
This input is into the variable "text" everytime the search button is clicked.
The Inputted word is then appended into the API request URL which returns the definition......which is stored in variable "result" in the bottom method OnPost Execute()
My TextView should then be set to this String.
I Therefore put the entire JSON and HTTPrequest code within the onClickLIstener because the user input always changes and requests everytime, but im getting an error at the "throws ClientProtocolException" after the "public JSONObject lastTweet(String word)" the error is "Syntax error on tokens, delete these tokens" I am Using Enclipse Indigo.
Here Is my Code:
public class Dictionary extends Activity {
String finalresult;
HttpClient client = new DefaultHttpClient();
TextView ansa;
JSONObject json;
Button Search;
EditText input;
String text;
final static String URL = "http://api.wordnik.com/v4/word.json/";
final static String URL2 = "/definitions?api_key=<MY API KEY>";
String fresult;
Dictionary dic = new Dictionary();
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.dictionary);
ansa = (TextView) findViewById(R.id.ansa);
input = (EditText) findViewById(R.id.input);
Search = (Button) findViewById(R.id.search);
Search.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
text = input.getText().toString();
public JSONObject lastTweet(String word)
throws ClientProtocolException, IOException, JSONException{
new Read().execute("text");
StringBuffer strBuff = new StringBuffer();
strBuff.append(URL);
strBuff.append(word);
strBuff.append(URL2);
HttpGet get = new HttpGet(strBuff.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200){
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(0);
return last;
}else{
Toast.makeText(Dictionary.this, "error", Toast.LENGTH_LONG);
return null;
}
}
class Read extends AsyncTask<String, Integer, String>{
#Override
public String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
json = lastTweet(text);
return json.getString(params[0]);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
fresult = result;
// TODO Auto-generated method stub
}
}
ansa.setText(fresult);
}
});
}
public JSONObject lastTweet(String word)
throws ClientProtocolException, IOException, JSONException{
new Read().execute("text");
StringBuffer strBuff = new StringBuffer();
strBuff.append(URL);
strBuff.append(word);
strBuff.append(URL2);
HttpGet get = new HttpGet(strBuff.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200){
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(0);
return last;
}else{
Toast.makeText(Dictionary.this, "error", Toast.LENGTH_LONG);
return null;
}
}
class Read extends AsyncTask<String, Integer, String>{
#Override
public String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
json = lastTweet(text);
return json.getString(params[0]);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
fresult = result;
// TODO Auto-generated method stub
}
}
}
Any Suggestions?
Have you tried moving the request code to another class?
I'm wondering how I can access the return statement with a static function. I have a static function with Async and I want to then get the return statement in another class - I know it sounds complex but, I'm sure it's an easy solution.
Login.class
public class LogIn extends Activity {
Button login;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
TextView top = (TextView) findViewById(R.id.textView2);
final EditText user = (EditText) findViewById(R.id.etUser);
final EditText pass = (EditText) findViewById(R.id.etPass);
CheckBox stay = (CheckBox) findViewById(R.id.cBStay);
Button login = (Button) findViewById(R.id.btLogin);
login.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String user1 = user.getText().toString();
String pass1 = pass.getText().toString();
if(user1 !=null &user1.length()>=1 & pass1 !=null &pass1.length()>=1) {
ComHelper.SendLogin(user1, pass1);
}
}
});
}
}
ComHelper.class
public class ComHelper extends AsyncTask<String, Void, String> {
static String adress ="http://gta5news.com/login.php";
String user;
String pass;
public static boolean SendLogin(String user1, String pass1){
String user = user1.toString();
String pass = pass1.toString();
new ComHelper().execute(user1, pass1, adress);
return true;
}
private static StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
InputStream inputStream = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost(adress);
try {
/*Add some data with NameValuePairs */
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("user", user));
nameValuePairs.add(new BasicNameValuePair("password", pass));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
/*Execute */
HttpResponse response = httpclient.execute(post);
String str = inputStreamToString(response.getEntity().getContent())
.toString();
Log.w("HttpPost", str);
if (str.toString().equalsIgnoreCase("true"))
return str;
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
return null;
}
}
Now, I want to see if ComHelper.SendLogin() returned true/or at least returned something.
EDIT: When the code is executed nothing happens, I guess that's because I'm not doing anything with the return statement.
You want to implement
protected void onPostExecute (Result result)
on your AsyncTask implementation. The result parameter will be whatever you return from the doInBackground method. Since this runs in the UI thread you can modify the UI how you want at that time.
If you want to look at the value, then you need to save the return value of the method in a local variable
if(user1 !=null && user1.length() > 0 && pass1 !=null && pass1.length() > 0)
{
boolean comLogin = ComHelper.SendLogin(user1, pass1);
if(comLogin)
{
//do something
}
}
class XXX implements Runnable
{
String lat,lon,str,taluka_name;
int name;
HttpResponse response;
HttpEntity entity;
InputStream is = null;
Toast s1;
StringBuilder sb=null;
TextView v;
Spinner s;
public String result[];
TextView tv;
LinearLayout ll1;
int i;
ArrayList<Integer> croplist;
public XXX(String t_n,String [] res,LinearLayout ll,TextView tv1)
{
croplist= new ArrayList<Integer>();
taluka_name = t_n;
result = res;
ll1= ll;
tv = tv1;
}
#Override
public void run() {
// TODO Auto-generated method stub
HttpClient httpclient = new DefaultHttpClient();
HttpPost request = new HttpPost("http://10.0.2.2/proagri115.php");
List<NameValuePair>login=new ArrayList<NameValuePair>();
login.add(new BasicNameValuePair("location", taluka_name));
try
{
UrlEncodedFormEntity entity=new UrlEncodedFormEntity(login);
request.setEntity(entity);
}
catch (UnsupportedEncodingException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
try
{
response = httpclient.execute(request);
entity = response.getEntity();
is = entity.getContent();
System.out.println("Executed the request");
}
catch (ClientProtocolException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
e.printStackTrace();
System.out.println("");
}
catch(Exception e)
{
}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
str=sb.toString();
Log.e("log_tag", "Success converting result "+sb.toString());
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
System.out.println(str+"I have executed");
result = str.split(">>");
System.out.println("length"+result.length);
for(i=0;i<result.length;i++)
{
System.out.println("\n"+i+"=="+result[i]);
}
System.out.println("Notified");
}
}
}
public class help extends Activity{
int j;
Intent i;
String s,taluka_name;
EditText edt,edt1,edt2;
Double lat,lon;
Spinner spin;
String [] re;
TextView tv;
Layout lt;
LinearLayout lt1;
XXX runnable;
public void onCreate(Bundle savedinstancestate)
{
super.onCreate(savedinstancestate);
setContentView(R.layout.help);
lt1 = (LinearLayout)findViewById(R.id.ll1);
s =(String)getIntent().getSerializableExtra("Rainfall");
taluka_name =(String)getIntent().getSerializableExtra("location");
System.out.println(s);
tv = new TextView(this);
tv.setText("Crops for Your Selected Area are");
lt1.addView(tv);
try
{
runnable = new XXX(taluka_name,re,lt1,tv);
Thread threadX = new Thread(runnable);
System.out.println("till this");
threadX.start();
System.out.println("In Waited");
try
{
wait(500);
}
catch (IllegalMonitorStateException e)
{
System.out.println("IllegalMonitorStateException");
}
catch (InterruptedException e)
{
System.out.println("InterruptedException");
}
System.out.println("Out of Waited");
}
catch(Exception e)
{
System.out.println("Error again "+e);
}
try{
System.out.println("Final Result will be");
for(j=0;j<runnable.result.length;j++)
{
tv = new TextView(this);
tv.setText(runnable.result[j]);
System.out.println(runnable.result[j]);
lt1.addView(tv);
}
}
catch(Exception e)
{
}
}
}
I have main activity and thread XXX. I want to use the result of httprequest in XXX thread to be used in Main activity.But before XXX completes its operation main thread executes and
I get NullpointerException . How should I use network response in main activity . I have tried "synchronized block" . But It works for methods of single class.
How should I solve this problem?
You should use a synchronization mechanism whenever two threads need to cooperate and exchange information.
You can use a Handler to post an action back to the UI thread when the HTTP request completes in the background thread or better yet perform the background work in AsyncTask.
Here is a general example:
private class AsyncTaskExample extends AsyncTask<Param, Progress, Result> {
#Override
protected Result doInBackground(Param... params) {
// Performs some computation in a background thread.
// Use publishProgress() to publish progress updates which
// will take place in the UI thread in onProgressUpdate().
return ...;
}
#Override
protected void onProgressUpdate(Progress... progress) {
// Update progress information. Run in the UI thread.
}
#Override
protected void onPostExecute(Result result) {
// Update on completion. Run in the UI thread.
}
}
Note that AsyncTask is a generic class and requires three parameters: Param for input data to the background computation, Result for the result of the computation and Progress to represent progress update information.
Note also that doInBackground() is the only abstract method in AsyncTask, so at minimum you must override just this one method. In most cases, you will find onPostExecute() and onProgressUpdate() very useful as well. For more overridable methods and details see AsyncTask.
Once you have defined a task class you can launch the computation it represents in the background by in the following way:
new AsyncTaskExample().execute(param1, param2, ...);
Passing parameters (of type Param) to execute(). Note that this must be done in the UI thread.
At minimum, you need to use Thread.join to wait for the thread to complete.. But that would block on your UI thread which is really bad. You should really just do this the android way and use an AsyncTask
Read this:
http://developer.android.com/resources/articles/painless-threading.html
Here is what you should do:
import android.os.AsyncTask;
public class XXX extends AsyncTask<Integer, Integer, String[]> {
String lat, lon, str, taluka_name;
int name;
HttpResponse response;
HttpEntity entity;
InputStream is = null;
Toast s1;
StringBuilder sb = null;
TextView v;
Spinner s;
public String result[];
TextView tv;
LinearLayout ll1;
int i;
ArrayList<Integer> croplist;
public XXX(String t_n, String[] res, LinearLayout ll, TextView tv1) {
croplist = new ArrayList<Integer>();
taluka_name = t_n;
result = res;
ll1 = ll;
tv = tv1;
}
#Override
protected String[] doInBackground(Integer... params) {
// TODO Auto-generated method stub
HttpClient httpclient = new DefaultHttpClient();
HttpPost request = new HttpPost("http://10.0.2.2/proagri115.php");
List<NameValuePair> login = new ArrayList<NameValuePair>();
login.add(new BasicNameValuePair("location", taluka_name));
try {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(login);
request.setEntity(entity);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
response = httpclient.execute(request);
entity = response.getEntity();
is = entity.getContent();
System.out.println("Executed the request");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
e.printStackTrace();
System.out.println("");
} catch (Exception e) {
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
str = sb.toString();
Log.e("log_tag", "Success converting result " + sb.toString());
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
System.out.println(str + "I have executed");
result = str.split(">>");
System.out.println("length" + result.length);
for (i = 0; i < result.length; i++) {
System.out.println("\n" + i + "==" + result[i]);
}
System.out.println("Notified");
}
return result;
}
}
Then from your activity call:
new XXX(taluka_name,re,lt1,tv).execute();
Now the tricky thing is you need to get that result back to your UI thread.. The easiest way is to put the AsyncTask within the activity as an inner class, then in onPostExecute of the asyncTask you just call some function from your activity.
If you want the AsyncTask in a seperate file then you need to pass a reference of your class to the constructor of the AsyncTask and then you can call any public method of your activity from the asyncTask. Just remember that you can only call the activities methods in onPostExecute and in onProgressUpdate (do not call UI methods in doInBackground)