Oxford Dictionary Api Search Word Through EditText - android

MainActivivity.java
package com.example.anubhav.notesapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity2 extends AppCompatActivity {
String url;
EditText et;
TextView t1;
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
et = (EditText)findViewById(R.id.editText2);
t1 = (TextView)findViewById(R.id.textView3);
btn = (Button)findViewById(R.id.button);
url = dictionaryEntries();
}
public void requestApiButtonClick(View v)
{
MyDictionaryRequest myDictionaryRequest = new MyDictionaryRequest(this,t1);
myDictionaryRequest.execute(url);
}
private String dictionaryEntries() {
final String language = "en";
final String word = et.getText().toString();
final String word_id = word.toLowerCase();
return "https://od-api.oxforddictionaries.com:443/api/v1/entries/" + language + "/" + word_id;
}
}
DictionaryRequest.java
public class MyDictionaryRequest extends AsyncTask<String,Integer,String> {
final String app_id = "your_apiId";
final String app_key = "Your api_key";
String myurl;
TextView t1;
Context context;
Handler h = new Handler();
MyDictionaryRequest(Context context,TextView t1){
this.context = context;
this.t1=t1;
}
#Override
protected String doInBackground(String... strings) {
myurl = strings[0];
try {
URL url = new URL(myurl);
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setRequestProperty("Accept","application/json");
urlConnection.setRequestProperty("app_id",app_id);
urlConnection.setRequestProperty("app_key",app_key);
// read the output from the server
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
return stringBuilder.toString();
}
catch (Exception e) {
e.printStackTrace();
return e.toString();
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
String def;
try{
JSONObject js = new JSONObject(s);
JSONArray results = js.getJSONArray("results");
JSONObject lentries = results.getJSONObject(0);
JSONArray lArray= lentries.getJSONArray("lexicalEntries");
JSONObject entries = lArray.getJSONObject(0);
JSONArray e = entries.getJSONArray("entries");
JSONObject senses = e.getJSONObject(0);
JSONArray sensesArray = senses.getJSONArray("senses");
JSONObject d = sensesArray.getJSONObject(0);
JSONArray de = d.getJSONArray("definitions");
def=de.getString(0);
t1.setText(def);
Toast.makeText(context,def,Toast.LENGTH_SHORT).show();
}catch (Exception e)
{
e.printStackTrace();
}
}
}
Everthing is working fine in this code except that I can't get the word's meaning through edit text.
To be more specific :
The code works fine when I add
final String word = "car";
in dictionaryEntries() under Mainactivity.java
but nothing is displayed when :
final String word = et.getText().toString();

you have to move one of your code :
public void requestApiButtonClick(View v) {
MyDictionaryRequest myDictionaryRequest = new MyDictionaryRequest(this, t1);
url = dictionaryEntries();
myDictionaryRequest.execute(url);
}

Related

API call with AsyncTask

I am trying to use android studio to access a streaming/internet API. My API call works in Eclipse without using AsyncTask so I'm trying to use AsyncTask in Android Studio to call the API but I'm not sure why it's not working. The way I use the buffered reader and input stream are the same as the way I used them in eclipse when the call works. I also have permission to use internet in my AndroidManifest.xml.
Note: I took out my API key for obvious reasons.
import android.content.Intent;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.os.AsyncTask;
import android.view.View;
import android.widget.EditText;
import android.view.View.OnClickListener;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
private static final String TAG_DEBUG = MainActivity.class.getName();
public static final String TAG_ID = "id";
public static final String TAG_CURRENTTEMP = "currenttemp";
public static final String TAG_MAXTEMP = "maxtemp";
public static final String TAG_MINTEMP = "mintemp";
private EditText enteredzip;
private String zip;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
enteredzip = (EditText) findViewById(R.id.editText);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
public void onClick(View v) {
zip = enteredzip.getText().toString();
new RetrieveFeedTask().execute();
}
class RetrieveFeedTask extends AsyncTask<Void, Void, String> {
private Exception exception;
protected void onPreExecute() {
}
protected String doInBackground(Void... urls) {
String BASE_URL = "http://api.openweathermap.org/data/2.5/weather?zip=";
String API_CALL = "&APPID=key";
// Do some validation here
HttpURLConnection con = null;
InputStream is = null;
String bufferedOutput = "";
try {
con = (HttpURLConnection) (new URL(BASE_URL + zip + API_CALL)).openConnection();
con.setRequestMethod("GET");
con.setDoInput(true);
con.setDoOutput(true);
con.connect();
StringBuffer buffer = new StringBuffer();
is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
while((line = br.readLine()) != null)
buffer.append(line + "\r\n");
is.close();
con.disconnect();
bufferedOutput = buffer.toString();
return bufferedOutput;
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
} finally {
try{
is.close();
}catch(Throwable T){}
try{
con.disconnect();
}catch(Throwable T){}
}
}
protected void onPostExecute(String response) {
if(response == null) {
//response = "THERE WAS AN ERROR";
//Toast.makeText(MainActivity.this, getResources().getString(R.string.error_et), Toast.LENGTH_LONG).show();
return;
}
//Log.i("INFO", response);
// TODO: check this.exception
// TODO: do something with the feed
Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();
String id = "";
String currenttemp = "";
String maxtemp = "";
String mintemp = "";
for (int i = 0; i < response.length(); i++) {
if (response.substring(i, i + 2).equals("id")) {
id = response.substring(i + 4, i + 7);
break;
}
}
for (int i = 0; i < response.length(); i++) {
if (response.substring(i, i + 4).equals("temp")) {
currenttemp = response.substring(i + 6, i + 9);
break;
}
}
for (int i = 0; i < response.length(); i++) {
if (response.substring(i, i + 8).equals("temp_min")) {
mintemp = response.substring(i + 10, i + 13);
break;
}
}
for (int i = 0; i < response.length(); i++) {
if (response.substring(i, i + 8).equals("temp_max")) {
maxtemp = response.substring(i + 10, i + 13);
break;
}
}
launchMain2Activity(id, currenttemp, maxtemp, mintemp);
}
}
private void launchMain2Activity(String id, String currenttemp, String maxtemp, String mintemp) {
Intent Main2Activity = new Intent(MainActivity.this, Main2Activity.class);
Main2Activity.putExtra(TAG_ID, id);
Main2Activity.putExtra(TAG_CURRENTTEMP, currenttemp);
Main2Activity.putExtra(TAG_MAXTEMP, maxtemp);
Main2Activity.putExtra(TAG_MINTEMP, mintemp);
startActivity(Main2Activity);
}
try to use this :
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")) ;
UTF-8 is a method for encoding Unicode characters using 8-bit sequences.

my app doesn't add weather info to TextView (JSON)

I recently started learning JSON to use in my apps. I found a weather API (openweathermap.org) and used it on my app. the app runs fine but when I press Button, nothing happens. my source code:
import android.content.Context;
import android.hardware.input.InputManager;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.*;
import java.net.*;
import java.util.*;
import android.util.*;
import android.view.*;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import org.json.*;
public class MainActivity extends AppCompatActivity {
EditText city;
TextView weather, description;
DownloadTask DownloadTask;
public void showWeather (View view)
{
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(city.getWindowToken(), 0);
try
{
String encodedCityName = URLEncoder.encode(city.getText().toString(), "UTF-8");
DownloadTask = new DownloadTask();
DownloadTask.execute("http://api.openweathermap.org/data/2.5/weather?q=" + encodedCityName + "&appid=812f300ec742971975bbde9a2e0ac0c1");
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Error!", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
city = (EditText) findViewById(R.id.city);
weather = (TextView) findViewById(R.id.weather);
description = (TextView) findViewById(R.id.description);
}
public class DownloadTask extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection connection = null;
try
{
url = new URL(urls[0]);
connection = (HttpURLConnection) url.openConnection();
InputStream in = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != 1)
{
char current = (char) data;
result += current;
data = reader.read();
}
return result;
}
catch (Exception e)
{
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Error!", Toast.LENGTH_LONG);
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.i("Weather content", result);
try
{
JSONObject jsonObject = new JSONObject(result);
String weatherInfo = jsonObject.getString("weather");
Log.i("Weather Content", weatherInfo);
JSONArray jsonArray = new JSONArray(weatherInfo);
String getMain = "";
String getDescription = "";
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject jsonPart = jsonArray.getJSONObject(i);
getMain = jsonPart.getString("main");
getDescription = jsonPart.getString("description");
Log.i("Main", getMain);
}
if (getMain != "" && getDescription != "")
{
weather.setText(getMain);
description.setText(getDescription);
}
}
catch (JSONException e)
{
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Error!", Toast.LENGTH_LONG);
}
}
}
}
none of Toasts and Logs work.
You have an error in reading the data. You should stop reading when getting -1 not 1.
while (data != -1)
{
char current = (char) data;
result += current;
data = reader.read();
}

App Crashes while switching from one Activity to another

Aim: Building app on Google API to fetch the data about the books the user searches
Problem Explanation:
Whenever I hit the submit Button, my app crashes.
This is my first approach in making a network request app and I need guidance.
MainActivityClass
package com.example.vidit.books;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText query = (EditText) findViewById(R.id.query);
Button submit= (Button) findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent= new Intent(MainActivity.this,Request.class);
intent.putExtra ( "text", query.getText().toString() );
startActivity(intent);
}
});
}
}
Second Class
package com.example.vidit.books;
import android.content.Intent;
public class Request {
Intent i = getIntent();
String text = i.getStringExtra ("text");
public static final String LOG_TAG = Request.class.getSimpleName();
String APIURL="https://www.googleapis.com/books/v1/volumes?q= " + text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_request);
}
public void UpdateUi(Book book)
{
BookAdapter bookAdapter = new BookAdapter(this,book);
ListView listView= (ListView) findViewById(R.id.listview_all);
}
private class BookAsyncTask extends AsyncTask<URL,Void,Book>
{
#Override
protected Book doInBackground(URL... urls) {
URL url = createUrl(APIURL);
String jsonResponse = "";
try {
jsonResponse = makeHttpRequest(url);
} catch (IOException e) {
// TODO Handle the IOException
}
final Book book = extractFeatureFromJson(jsonResponse);
return book;
}
/**
* Make an HTTP request to the given URL and return a String as the response.
*/
private String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.connect();
if(urlConnection.getResponseCode()==200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
}
} catch (IOException e) {
// TODO: Handle the exception
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
// function must handle java.io.IOException here
inputStream.close();
}
}
return jsonResponse;
}
/**
* Convert the {#link InputStream} into a String which contains the
* whole JSON response from the server.
*/
private String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
/**
* Returns new URL object from the given string URL.
*/
private URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException exception) {
Log.e(LOG_TAG, "Error with creating URL", exception);
return null;
}
return url;
}
private Book extractFeatureFromJson(String bookJSON) {
try {
JSONObject baseJsonResponse = new JSONObject(bookJSON);
JSONArray items = baseJsonResponse.getJSONArray("items");
// If there are results in the features array
for(int i=0;i<10;i++)
{
JSONObject firstFeature = items.getJSONObject(i);
JSONArray author=firstFeature.getJSONArray("author");
for(int j=0;j<author.length();j++)
{
JSONObject authorFeature=author.getJSONObject(j);
}
String title = items.getString(Integer.parseInt("title"));
// Create a new {#link Event} object
return new Book(title,author);
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Problem parsing the earthquake JSON results", e);
}
return null;
}
}
}
BookAdapter Class:
package com.example.vidit.books;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
public class BookAdapter extends ArrayAdapter<Book> {
public BookAdapter(Activity context, Book book)
{
super(context,0, (List<Book>) book);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if(listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
Book cbook=getItem(position);
TextView title = (TextView) listItemView.findViewById(R.id.title);
title.setText(cbook.getmTitle());
TextView author=(TextView) listItemView.findViewById(R.id.author);
author.setText((CharSequence) cbook.getmAuthor());
return listItemView;
}
}
Showing error in statement:
String text = i.getStringExtra ("text");
Need guidance
I don't know how your code gets compiled when you have overridden onCreate() in Request class and the Request class isn't extending Activity or AppCompatActivity.
Secondly, this line :
Intent i = getIntent();
String text = i.getStringExtra ("text");
should be inside the onCreate() method.
Showing error in statement : String text = i.getStringExtra ("text");
Request for Guidance
Well you need to get the data passed inside onCreate like below.
String APIURL;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_request);
Bundle bundle = getIntent().getExtras();
String text = bundle.getString("text");
APIURL="https://www.googleapis.com/books/v1/volumes?q= " + text;
}
And although you have the asyncTask class i can't see where exactly you execute the class. You need to do that inside onCreate as well.
Try moving this code to your onCreate method
Intent i = getIntent();
String text = i.getStringExtra ("text");
The intent extras is not available in the constructor for your Request class.

Android: get as a static String a value from a URL

URL = http://troyka.esy.es/numberofrows.php
if you put that in your browser you'l get a number (currently it's 9)
I'm trying to pull that number to my android app and display it on a textview
I've tried this method but it shows me nothing on the emulator
internet and network permission are set on manifest
textview id = "textView"
What am I doing wrong?
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
public class MainActivity extends Activity {
public static String ans;
private TextView T1;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
T1 = new TextView(this);
T1 = (TextView) findViewById(R.id.textView);
T1.setText(ans);
}
public String getDATA() throws IOException {
String fullString = "";
URL url = new URL("http://troyka.esy.es/numberofrows.php");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null) {
fullString += line;
}
reader.close();
return fullString;
}
public void setAns() throws IOException {
ans = getDATA();
}
}
Try this answer please:
First, create an AsyncTask class like this to do the actual HTTP request for you outside the android main thread:
public class FetchColumnAsync extends AsyncTask<String, Void, String>
{
private Context mContext;
public FetchColumnAsync( Context ctx){
this.mContext = ctx;
}
protected String doInBackground(String... urls)
{
String fullString = "";
try{
URL url = new URL(urls[0]);
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null) {
fullString += line;
}
reader.close();
}catch(Exception e ){
e.getMessage();
}
return fullString;
}
#Override
protected void onPostExecute(String value){
try{
((OnValueFetchedListener) mContext).onValueFetched(value);
}catch(ClassCastException e){}
}
public interface OnValueFetchedListener{
void onValueFetched(String columns);
}
}
Then in your activity class, implement the above interface like this;
public class MainActivity extends Activity implements FetchColumnAsync.OnValueFetchedListener{
public static String ans;
private TextView T1;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
T1 = (TextView) findViewById(R.id.textView);
//missing piece of code here
new FetchColumnAsync(this).execute("http://troyka.esy.es/numberofrows.php");
}
#Override
public void onValueFetched(String value){
T1.setText(value);
}
}

Asynctask getActivity

I am trying to set my toolbar title from an async task. I am getting a cannot resolve method getActivity() in this line:
((ActionBarActivity)getActivity()).getSupportActionBar().setTitle(name);
My code looks like this:
/**
* Created by Mike on 2/28/15.
*/
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
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.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* Created by Mike on 4/26/14.
*/
public class GetBeerDataJSON2 extends AsyncTask<String, Void, String> {
Context c;
String id;
private ProgressDialog Dialog;
public GetBeerDataJSON2 (Context context, String beerID)
{
c = context;
id = beerID;
Dialog = new ProgressDialog(c);
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPreExecute() {
Dialog.setMessage("Getting beer information");
Dialog.setTitle("Loading");
Dialog.show();
}
protected void onPostExecute(String result){
//decode json here
try{
JSONObject o = new JSONObject(result);
//get beer details
//todo: lets get things from our new JSON
String name = o.getString("name");
String beerDescription = o.getString("description");
String abv = o.getString("abv");
String ibu = o.getString("ibu");
String image = o.getString("icon");
String glass = o.getString("glass");
String beerBreweryStyle = o.getString("style");
String beerBreweryName = o.getString("brewery");
String status = o.getString("status");
String rating = o.getString("rating");
String food = o.getString("food");
int beerRate = 0;
beerRate = o.getInt("userRating");
//prepare buttons
//Button buttonBrewery = (Button) ((Activity) c).findViewById(R.id.buttonBrewery);
//Button buttonStyle = (Button) ((Activity) c).findViewById(R.id.buttonStyle);
TextView tv_breweryName = (TextView) ((Activity) c).findViewById(R.id.beerBreweryName);
TextView tv_styleName = (TextView) ((Activity) c).findViewById(R.id.beerStyleName);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(c);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("styleName",beerBreweryStyle);
editor.putString("beerName",name);
editor.putString("lastBeer",name);
editor.putString("breweryName",beerBreweryName);
editor.putString("styleName",beerBreweryStyle);
editor.commit();
((ActionBarActivity)getActivity()).getSupportActionBar().setTitle(name);
//create text views
TextView styleTitle = (TextView) ((Activity) c).findViewById(R.id.beerTitle);
styleTitle.setText(name);
TextView textABV = (TextView) ((Activity) c).findViewById(R.id.abv);
textABV.setText(abv);
TextView textIBU = (TextView) ((Activity) c).findViewById(R.id.IBU);
textIBU.setText(ibu);
TextView textGlass = (TextView) ((Activity) c).findViewById(R.id.glass);
textGlass.setText(glass);
TextView textDescription= (TextView) ((Activity) c).findViewById(R.id.beerDescription);
textDescription.setText(beerDescription);
String breweryButton = "Brewery: ";
String styleButton = "Style: ";
//todo: add beer name to shared prefs
tv_breweryName.setText(beerBreweryName);
tv_styleName.setText(beerBreweryStyle);
//get user id
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);
String userName = prefs.getString("userName", null);
final String userID = prefs.getString("userID", null);
//check if user has beer
String url = "http://www.beerportfolio.com/app_checkBeer.php?";
String userURLComp = "u=" + userID;
final String beerID = "&b=" + id;
url = url + userURLComp + beerID;
//new CheckBeerJSON(c,id,userID).execute(url);
//todo: add code for check beer here
if(status.equals("no")){
//clear loader image
LinearLayout ll = (LinearLayout) (LinearLayout)((Activity) c).findViewById(R.id.addBeerLayout);
ll.removeAllViews();
//Add beer add button
LayoutInflater mInflater = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout addButton = (LinearLayout)((Activity) c).findViewById(R.id.addBeerLayout);
addButton.addView(mInflater.inflate(R.layout.addbeerbutton_layout, null));
//add on click listener here
Button bt4 = (Button)((Activity) c).findViewById(R.id.button1);
bt4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// do whatever stuff you wanna do here
//get beer details
String url2 = "http://www.beerportfolio.com/app_addBeer.php?";
String urlUserID = "u=" + userID;
String urlBeerID = "&bID=" + id;
Log.d("url", id);
//construct url for adding beer
url2 = url2 + urlUserID + urlBeerID;
Log.d("url", url2);
//execute async on url to add to brewery
new AddBeer(c).execute(url2);
//to do: change to start rater
LinearLayout ll = (LinearLayout) ((Activity) c).findViewById(R.id.addBeerLayout);
ll.removeAllViews();
//add rater
LayoutInflater inflater = (LayoutInflater)((Activity) c).getSystemService(((Activity) c).LAYOUT_INFLATER_SERVICE);
LinearLayout addButton = (LinearLayout)((Activity) c).findViewById(R.id.addBeerLayout);
addButton.addView(inflater.inflate(R.layout.addrate_layout, null));
//add listener to rate button todo
//add listener to bar
addListenerOnRatingBar(c);
}
});
}
else{
//clear loader image
LinearLayout ll = (LinearLayout) (LinearLayout)((Activity) c).findViewById(R.id.addBeerLayout);
ll.removeAllViews();
//inflate star rater
LayoutInflater mInflater = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout addButton = (LinearLayout)((Activity) c).findViewById(R.id.addBeerLayout);
addButton.addView(mInflater.inflate(R.layout.addrate_layout, null));
RatingBar r = (RatingBar) ((Activity) c).findViewById(R.id.beerRatingBar);
//get user data
//get beer rating with async task and update rate bar
String url2 = "http://www.beerportfolio.com/app_getRating.php?";
String userURLComp2 = "u=" + userID;
String beerID2 = "&b=" + beerID;
url = url + userURLComp2 + beerID2;
//new GetUserRating(c,r).execute(url2);
r.setRating(beerRate);
//add listener to bar
addListenerOnRatingBar(c);
}
//end code here
//todo: get rate code goes here
TextView tv1 = (TextView) ((Activity) c).findViewById(R.id.beerRating);
tv1.setText(rating + " / 5");
//end rate code
String url2 = "http://beerportfolio.com/app_beerDetails2.php?u="+ userID + "&b=" + beerID;
//new GetBeerRateJSON(c,id).execute(url2);
ImageView im1 = (ImageView) ((Activity) c).findViewById(R.id.image);
if(image.equals("N/A")){
//set image as png
im1.setImageResource( R.drawable.noimage);
}
else{
ImageDownloadTask imageD = new ImageDownloadTask(im1);
imageD.execute(image);
}
//tdo: add food paring
if (food.equals("N/A")){
}
Dialog.dismiss();
}
catch(Exception e){
}
}
private void addListenerOnRatingBar(Context view) {
RatingBar ratingBar = (RatingBar) ((Activity) view).findViewById(R.id.beerRatingBar);
ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromUser) {
//next async task to update online database
float stars = ratingBar.getRating();
//get user details
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);
String userID = prefs.getString("userID", null);
//get beer id
String beerID = id;
//get rating
String urlRate = "r=" + String.valueOf(ratingBar.getRating());
String urlUserID = "&u=" + userID;
String urlBeerID = "&b=" + beerID;
//construct url
String url2 = "http://www.beerportfolio.com/app_rateUpdate.php?";
url2 = url2 + urlRate + urlUserID + urlBeerID;
//async task to update rating in database
new UpdateRating(c).execute(url2);
}
});
}
public String getName(JSONObject json){
String holder;
try{
holder = json.getJSONObject("data").getString("name");
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
public String getABV(JSONObject json){
String holder;
try{
holder = json.getJSONObject("data").getString("abv");
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
public String getIBU(JSONObject json){
String holder;
try{
holder = json.getJSONObject("data").getString("ibu");
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
public String getImage(JSONObject json){
String holder;
try{
holder = json.getJSONObject("data").getJSONObject("labels").getString("large");
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
public String getGlass(JSONObject json){
String holder;
try{
holder = json.getJSONObject("data").getJSONObject("glass").getString("name");
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
public String getBreweryName(JSONObject json){
String holder;
try{
holder = json.getJSONObject("data").getJSONArray("breweries").getJSONObject(0).getString("name");
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
public String getBreweryStyle(JSONObject json){
String holder;
try{
holder = json.getJSONObject("data").getJSONObject("style").getString("name");
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
public String getDescription(JSONObject json){
String holder;
try{
holder = json.getJSONObject("data").getString("description");
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
}
I feel like I need to use the context c that I bring in, but every combination I have tried has failed me.
Use context:
((ActionBarActivity)context).getSupportActionBar().setTitle(name);
At first you should do all time consuming operation in a doInBackground method. This also include parsing JSON data. In onPreExecute and onPostExecute method you should do only GUI things.
Don't use activity or activity context directly in AsyncTask class. Use listeners together with WeakReference to change GUI things. For example:
public class MyAsyncTask extends AsyncTask<String, Void, String> {
public interface TaskListener {
void onTitleReceived(String title);
}
private final WeakReference<TaskListener> mTaskListenerRef;
public MyAsyncTask(TaskListener listener) {
this.mTaskListenerRef = new WeakReference<>(listener);
}
public void notifyTitleReceived(String title) {
TaskListener listener = mTaskListenerRef.get();
if (listener != null) {
listener.onTitleReceived(title);
}
}
protected void onPostExecute(String result){
...
notifyTitleReceived(newTitle);
...
}
}
public class MyActivity extends ActionBarActivity implements MyAsyncTask.TaskListener {
#Override
public void onTitleReceived(String title) {
getSupportActionBar().setTitle(title);
}
private void runTask() {
new MyTask(this).execute();
}
}
define an static instance of actvity , set it before excute()
in your GetBeerDataJSON2 class
public static ActionBarActivity instance = null;
in your ActionBarActivity class :
onCreate(Bundle bundle){
GetBeerDataJSON2 task = new GetBeerDataJSON2() ;
task.instance = this;
task.excute();
}
another solotion is passing this as the contextin your constructor of GetBeerDataJSON2 and cast it to ActionBarActivity
anyway better way of doing this is using libraries like volley to get json rather than building the wheel
Combining answers in constructor while creating instance of GetBeerDataJSON2(Context, Stirng) in Activity code pass 'this' as first argument.
And cast it as :
((ActionBarActivity) context).getSupportActionBar().setTitle(name);
Instead of :
((ActionBarActivity)getActivity()).getSupportActionBar().setTitle(name);
Error Because there is no method getActivity() defined for AsynchTask.

Categories

Resources