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.
Related
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);
}
NOTE :
First of all before writing any thing. this is not a duplicate because if it is then why I will post this here. I didn't find any of the stackoverflow similar questions' answers helpful to me at all for 2 days straight.
THE PROBLEM :
I have an activity that takes two fields of data and then go to the next activity where it has a view pager and the activity opens 2 fragments the posts and the profile. the problem here is that when I go back to the first activity to input different data and go to the fragments the listview shows duplicate data.
I tried every possible solution but none works.
I tried to clear adapter.
I tried to pass empty adapter.
I tried more things in the life cycle of the fragment but nothing.
so please I need help. thanks in advance.
package psychrating.psychrating;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by Ahmeed on 8/7/2017.
*/
public class PostsFragment extends Fragment {
static ListView posts_list;
Spinner list_order;
SearchView search;
String category, date, activity;
boolean get_data;
public static ArrayList<String> data = null;
static Context c;
transient ViewHolder holder;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
data = null;
activity = getArguments().getString("activity");
category = getArguments().getString("category");
date = getArguments().getString("date");
if (activity == "main") {
// get_data = true;
}else {
// get_data = true;
}
View view = inflater.inflate(R.layout.post_tab, container, false);
init(view);
posts_list.clearChoices();
if (searchResultses != null) {
searchResultses.clear();
searchResultses = null;
}
return view;
}
private void init(View view) {
posts_list = (ListView) view.findViewById(R.id.posts_list);
list_order = (Spinner) view.findViewById(R.id.list_order);
search = (SearchView) view.findViewById(R.id.search);
posts_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
holder = (ViewHolder) view.getTag();
Temp temp = new Temp();
temp.name = holder.name.getText().toString();
temp.highest = holder.highest.getText().toString();
temp.dname = holder.dname.getText().toString();
temp.date = holder.date.getText().toString();
temp.category = holder.category;
temp.sdesc = holder.sdesc;
temp.ddesc = holder.ddesc;
Intent i = new Intent(c, ProfileActivity.class);
i.putExtra("holder", temp);
startActivity(i);
}
});
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
c = context;
}
#Override
public void onResume() {
super.onResume();
searchResultses = new ArrayList<>();
new Server(this.getActivity(), "posts").execute(category, date);
}
public static final String TAG ="ahmed";
static void removeCommas() {
StringBuilder word = new StringBuilder();
for (int i = 0; i < data.size(); i++) {
for (int j = 0; j < data.get(i).length(); j++) {
char c = data.get(i).charAt(j);
if (c != ',') {
word.append(c);
}else {
words.add(word.toString());
word.delete(0, word.length());
}
}
}
}
#Override
public void onPause() {
super.onPause();
searchResultses = null;
adapter = null;
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
static void addToClass() {
SearchResults s;
int offset = 0;
for (int j = 0; j < words.size(); j += 8) {
Log.d(TAG, String.valueOf(words.size()));
s = new SearchResults();
for (int i = 0; i < 8; i++) {
offset = 1;
s.add(words.get(i * offset));
}
offset += 1;
s.init();
searchResultses.add(s);
}
}
static ArrayList<SearchResults> searchResultses = null;
static ArrayList<String> words = new ArrayList<>();
static MyCustomBaseAdapter adapter = null;
public static void fillList() {
removeCommas();
addToClass();
ArrayList<SearchResults> empty = new ArrayList<>();
adapter = new MyCustomBaseAdapter(c, empty);
adapter = new MyCustomBaseAdapter(c, searchResultses);
posts_list.setAdapter(adapter);
}
}
NOTE:
the fillList is a func that is being called by the asynctask when it finished retrieving data . which use the data variable and remove commas from data and add words to searchResult class
package psychrating.psychrating;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.io.Serializable;
import java.util.ArrayList;
/**
* Created by Ahmeed on 8/10/2017.
*/
public class MyCustomBaseAdapter extends BaseAdapter {
private static ArrayList<SearchResults> searchArrayList = null;
private LayoutInflater mInflater;
public MyCustomBaseAdapter(Context context, ArrayList<SearchResults> results) {
super();
searchArrayList = results;
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return searchArrayList.size();
}
public Object getItem(int position) {
return searchArrayList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.name.setText(searchArrayList.get(position).getName());
holder.highest.setText(searchArrayList.get(position).getHighest());
holder.dname.setText(searchArrayList.get(position).getDName());
holder.date.setText(searchArrayList.get(position).getDate());
holder.category = searchArrayList.get(position).getCategory();
holder.sdesc = searchArrayList.get(position).getSdesc();
holder.ddesc = searchArrayList.get(position).getDdesc();
convertView.setTag(holder);
return convertView;
}
}
Server class
package psychrating.psychrating;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
/**
* Created by Ahmeed on 8/6/2017.
*/
public class Server extends AsyncTask<String, String, String> {
private Context context;
private ProgressDialog progressDialog;
private AlertDialog.Builder builder;
private String type;
private static ArrayList<String> data = null;
Server(Context context, String type) {
this.context = context;
this.type = type;
}
private void createPreDialog(String message) {
progressDialog = new ProgressDialog(context);
progressDialog.setMessage(message);
progressDialog.setCancelable(false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
progressDialog.create();
}
progressDialog.show();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
createPreDialog("hold on");
}
#Override
protected String doInBackground(String... params) {
switch (type) {
case "login":
String personName = params[0];
String personEmail = params[1];
String id = params[2];
//
OutputStreamWriter outputStreamWriter = null;
BufferedWriter writer = null;
BufferedReader bufferedReader = null;
HttpURLConnection connection = null;
String line;
String result = null;
try {
URL url = new URL("http://192.168.1.64/blabla/sign_in.php");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setConnectTimeout(8000);
outputStreamWriter = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
writer = new BufferedWriter(outputStreamWriter);
String parameters = "name=" + personName + "&email=" + personEmail + "&id=" + id;
writer.write(parameters);
writer.flush();
if (connection.getResponseCode() == 200) {
bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = bufferedReader.readLine()) != null) {
result = line;
}
} else {
result = "Server Error";
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (outputStreamWriter != null) {
outputStreamWriter.close();
}
if (connection != null) {
connection.disconnect();
}
if (bufferedReader != null) {
bufferedReader.close();
}
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
case "posts":
String category = params[0];
String date = params[1];
//
OutputStreamWriter outputStreamWriter1 = null;
BufferedWriter writer1 = null;
BufferedReader bufferedReader1 = null;
HttpURLConnection connection1 = null;
String line1 = "";
String result1 = null;
try {
URL url1 = new URL("http://192.168.1.64/blabla/posts.php");
connection1 = (HttpURLConnection) url1.openConnection();
connection1.setRequestMethod("POST");
connection1.setDoOutput(true);
connection1.setDoInput(true);
connection1.setConnectTimeout(8000);
outputStreamWriter1 = new OutputStreamWriter(connection1.getOutputStream(), "UTF-8");
writer1 = new BufferedWriter(outputStreamWriter1);
String parameters1 = "category="+category+"&date="+date;
writer1.write(parameters1);
writer1.flush();
data = new ArrayList<>();
if (connection1.getResponseCode() == 200) {
bufferedReader1 = new BufferedReader(new InputStreamReader(connection1.getInputStream()));
while ((line1 = bufferedReader1.readLine()) != null) {
data.add(line1);
}
} else {
result1 = "Server Error";
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (outputStreamWriter1 != null) {
outputStreamWriter1.close();
}
if (connection1 != null) {
connection1.disconnect();
}
if (bufferedReader1 != null) {
bufferedReader1.close();
}
if (writer1 != null) {
writer1.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result1;
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressDialog.dismiss();
switch (type) {
case "login":
switch (s) {
case "Connect Error":
createDialog(s);
break;
case "Done":
Toast.makeText(context, s, Toast.LENGTH_LONG).show();
MainActivity.updateUI(true);
break;
case "Already Exist":
MainActivity.updateUI(true);
break;
case "Server Error":
createDialog(s);
break;
}
break;
case "posts":
if (data != null) {
PostsFragment.data = data;
PostsFragment.fillList();
data = null;
}
}
}
private void createDialog(String message) {
builder = new AlertDialog.Builder(context);
builder.setTitle("Error");
builder.setMessage(message);
builder.setCancelable(false);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create();
builder.show();
}
}
Your words in PostsFragment.java makes you element duplicate, In removeCommas() method first clears the words and then add the values to the words from data.
try this. searchResultses.clear(); at the start of addToClass()
static void addToClass() {
SearchResults s;
searchResultses.clear();
int offset = 0;
for (int j = 0; j < words.size(); j += 8) {
Log.d(TAG, String.valueOf(words.size()));
s = new SearchResults();
for (int i = 0; i < 8; i++) {
offset = 1;
s.add(words.get(i * offset));
}
offset += 1;
s.init();
searchResultses.add(s);
}
}
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.
I have a form having one edittext and an autocompleteview. And a button to search things based on this form. In this form I can either give value in edittext and autocompleteview may be empty and vice versa. On this basis I have passed value of these view to another activity where I made a webservice call and then fetch result.
This is activity where these view are presents:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_patient_section);
getSupportActionBar().hide();
searchByNameEditText = (EditText) findViewById(R.id.searchByNameEditText);
searchByAddressEditText = (EditText) findViewById(R.id.searchByAddressEditText);
searchButton = (Button) findViewById(R.id.searchButton);
autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.selectStateSpinner);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_dropdown_item_1line,
getResources().getStringArray(R.array.state_arrays));
autoCompleteTextView.setAdapter(adapter);
patientUtilityButton = (Button) findViewById(R.id.patientUtilityButton);
patientUtilityButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(PatientSectionActivity.this, patientUtilityButton);
popupMenu.getMenuInflater().inflate(R.menu.patient_utility_button_popmenu, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
String patientUtilityMenuItem = item.toString();
patientUtilityButton.setText(patientUtilityMenuItem);
return true;
}
});
popupMenu.show();
}
});
autoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectedStateValue = (String) parent.getItemAtPosition(position);
}
});
doctorName = searchByNameEditText.getText().toString();
// Search Button
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!selectedStateValue.equals(" ") || doctorName.equals(" ")){
Intent intent = new Intent(PatientSectionActivity.this, DoctorNameActivity.class);
intent.putExtra("State Name", selectedStateValue);
startActivity(intent);
} else if (!doctorName.equals(" ") || selectedStateValue.equals(" ")){
Intent intent = new Intent(PatientSectionActivity.this, DoctorNameActivity.class);
intent.putExtra("Name", doctorName);
startActivity(intent);
}
}
});
}
And in other activity, I get these extras from intent and make webservice call in AsyncTask but my app is crashing. Please any one help me as I am new in android.
This is my other activity
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class DoctorNameActivity extends ActionBarActivity {
ArrayAdapter<String> doctorAdapter;
ListView listView;
ProgressBar progressBar;
String doctorName;
String selectedStateValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doctor_name);
progressBar = (ProgressBar) findViewById(R.id.progress);
listView = (ListView) findViewById(R.id.listView);
Intent intent = getIntent();
selectedStateValue = intent.getStringExtra("State Name");
doctorName = intent.getStringExtra("Name");
if (!selectedStateValue.equals(" ") || doctorName.equals(" ")){
FetchDoctorName fetchDoctorName = new FetchDoctorName();
fetchDoctorName.execute(selectedStateValue);
}else if (!doctorName.equals(" ") || selectedStateValue.equals(" ")){
FetchDoctorName fetchDoctorName = new FetchDoctorName();
fetchDoctorName.execute(doctorName);
}
}
private class FetchDoctorName extends AsyncTask<String, Void, String[]>{
private final String LOG_TAG = FetchDoctorName.class.getSimpleName();
public String[] parseDoctorName(String jsonString) throws JSONException{
final String DOCTOR_NAME_ARRAY = "name";
JSONObject object = new JSONObject(jsonString);
JSONArray array = object.getJSONArray(DOCTOR_NAME_ARRAY);
String[] doctorNamesResult = new String[array.length()];
for (int i = 0 ; i < array.length(); i++){
String doctorName = array.getString(i);
Log.v(LOG_TAG, doctorName);
doctorNamesResult[i] = doctorName;
}
return doctorNamesResult;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(ProgressBar.VISIBLE);
}
#Override
protected String[] doInBackground(String... params) {
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String doctorJsonString = null;
try {
final String BASE_URL = "http://mycityortho.com/display_result.php";
final String NAME_PARAM = "name";
final String STATE_PARAM = "state";
URL url = null;
if (params[0].equals(doctorName)){
Uri uri = Uri.parse(BASE_URL).buildUpon()
.appendQueryParameter(NAME_PARAM, params[0])
.build();
url = new URL(uri.toString());
Log.v(LOG_TAG, url.toString());
}else if (params[0].equals(selectedStateValue)){
Uri uri = Uri.parse(BASE_URL).buildUpon()
.appendQueryParameter(STATE_PARAM, params[0])
.build();
url = new URL(uri.toString());
Log.v(LOG_TAG, url.toString());
}
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
doctorJsonString = buffer.toString();
Log.v(LOG_TAG, doctorJsonString);
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
try {
return parseDoctorName(doctorJsonString);
}catch (JSONException e){
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String[] result) {
progressBar.setVisibility(ProgressBar.GONE);
if (result != null){
doctorAdapter = new ArrayAdapter<>(DoctorNameActivity.this, android.R.layout.simple_list_item_1, result);
listView.setAdapter(doctorAdapter);
}
}
}
As per your code you are sending only one value in intent that is "State Name" or "Name" but in other activity you are trying to receive both value, that why you get null pointer exception.
So use the following code to solve this error.
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!selectedStateValue.equals(" ") || doctorName.equals(" ")){
Intent intent = new Intent(PatientSectionActivity.this, DoctorNameActivity.class);
intent.putExtra("State Name", selectedStateValue);
intent.putExtra("Name", " ");
startActivity(intent);
} else if (!doctorName.equals(" ") || selectedStateValue.equals(" ")){
Intent intent = new Intent(PatientSectionActivity.this, DoctorNameActivity.class);
intent.putExtra("State Name", " ");
intent.putExtra("Name", doctorName);
startActivity(intent);
}
}
});
very new to android and wondering how I can make this sample code return to where it left off instead of having to reload the pictures on returning to the screen. Right now when I exit the screen and return I have to start all over. I have read and trying to understand the Android documents but having trouble making this work or where to begin... thanks everyone!
package com.windmillagency;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
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.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
public class AndroidFlickrActivity extends BT_activity_base {
public String thisActivityName = "Flickr";
ProgressDialog progressDialog;
BackgroundThread backgroundThread;
public class FlickrImage {
String Id;
String Owner;
String Secret;
String Server;
String Farm;
String Title;
Bitmap FlickrBitmap;
FlickrImage(String _Id, String _Owner, String _Secret,
String _Server, String _Farm, String _Title){
Id = _Id;
Owner = _Owner;
Secret = _Secret;
Server = _Server;
Farm = _Farm;
Title = _Title;
FlickrBitmap = preloadBitmap();
}
private Bitmap preloadBitmap(){
Bitmap bm= null;
String FlickrPhotoPath =
"http://farm" + Farm + ".static.flickr.com/"
+ Server + "/" + Id + "_" + Secret + "_m.jpg";
URL FlickrPhotoUrl = null;
try {
FlickrPhotoUrl = new URL(FlickrPhotoPath);
HttpURLConnection httpConnection
= (HttpURLConnection) FlickrPhotoUrl.openConnection();
httpConnection.setDoInput(true);
httpConnection.connect();
InputStream inputStream = httpConnection.getInputStream();
bm = BitmapFactory.decodeStream(inputStream);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bm;
}
public Bitmap getBitmap(){
return FlickrBitmap;
}
}
class FlickrAdapter extends BaseAdapter{
private Context context;
private FlickrImage[] FlickrAdapterImage;;
FlickrAdapter(Context c, FlickrImage[] fImage){
context = c;
FlickrAdapterImage = fImage;
}
public int getCount() {
// TODO Auto-generated method stub
return FlickrAdapterImage.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return FlickrAdapterImage[position];
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView image;
if (convertView == null) {
image = new ImageView(context);
image.setLayoutParams(new Gallery.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
image.setScaleType(ImageView.ScaleType.FIT_CENTER);
image.setPadding(8, 8, 8, 8);
} else {
image = (ImageView) convertView;
}
image.setImageBitmap(FlickrAdapterImage[position].getBitmap());
return image;
}
}
FlickrImage[] myFlickrImage;
/*
* FlickrQuery = FlickrQuery_url
* + FlickrQuery_per_page
* + FlickrQuery_nojsoncallback
* + FlickrQuery_format
* + FlickrQuery_tag + q
* + FlickrQuery_key + FlickrApiKey
*/
String FlickrQuery_url = "http://api.flickr.com/services/rest/?method=flickr.people.getPublicPhotos&api_key=fdd73dc07613841fbe325b5103d673b7&user_id=65005067#N08&per_page=25&format=json";
String FlickrQuery_per_page = "&per_page=10";
String FlickrQuery_nojsoncallback = "&nojsoncallback=1";
String FlickrQuery_format = "&format=json";
String FlickrQuery_tag = "&tags=";
String FlickrQuery_key = "&api_key=";
// Apply your Flickr API:
// www.flickr.com/services/apps/create/apply/?
String FlickrApiKey = "fdd73dc07613841fbe325b5103d673b7";
final String DEFAULT_SEARCH = "flickr";
EditText searchText;
Button searchButton;
Gallery photoBar;
Bitmap bmFlickr;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.activityName = "AndroidFlickrActivity";
BT_debugger.showIt(activityName + ":onCreate");
//reference to base layout..
LinearLayout baseView = (LinearLayout)findViewById(R.id.baseView);
//setup background colors...
BT_viewUtilities.updateBackgroundColorsForScreen(this, this.screenData);
//setup background images..
if(backgroundImageWorkerThread == null){
backgroundImageWorkerThread = new BackgroundImageWorkerThread();
backgroundImageWorkerThread.start();
}
//setup navigation bar...
LinearLayout navBar = BT_viewUtilities.getNavBarForScreen(this, this.screenData);
if(navBar != null){
baseView.addView(navBar);
}
//inflate this screens layout file...
LayoutInflater vi = (LayoutInflater)thisActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View thisScreensView = vi.inflate(R.layout.flickr, null);
//add the view to the base view...
baseView.addView(thisScreensView);
searchText = (EditText)findViewById(R.id.searchtext);
searchText.setText(DEFAULT_SEARCH);
searchButton = (Button)findViewById(R.id.searchbutton);
photoBar = (Gallery)findViewById(R.id.photobar);
searchButton.setOnClickListener(searchButtonOnClickListener);
}
///////////////////////////////////////////////////
//activity life-cycle overrides
//onResume
#Override
public void onResume() {
super.onResume();
//Log.i("ZZ", thisActivityName + ":onResume");
tToast("onResume");
}
private void tToast(String s) {
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, s, duration);
toast.show();
}
//onPause
#Override
public void onPause() {
//Log.i("ZZ", thisActivityName + ":onPause");
super.onPause();
tToast("onPause");
}
//activity life-cycle overrides
///////////////////////////////////////////////////
private Button.OnClickListener searchButtonOnClickListener
= new Button.OnClickListener(){
public void onClick(View arg0) {
// TODO Auto-generated method stub
progressDialog = ProgressDialog.show(AndroidFlickrActivity.this,
"Progress", "Please Wait");
backgroundThread = new BackgroundThread();
backgroundThread.setRunning(true);
backgroundThread.start();
}};
private String QueryFlickr(String q){
String qResult = null;
String qString =
FlickrQuery_url
+ FlickrQuery_per_page
+ FlickrQuery_nojsoncallback
+ FlickrQuery_format
+ FlickrQuery_tag + q
+ FlickrQuery_key + FlickrApiKey;
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(qString);
try {
HttpEntity httpEntity = httpClient.execute(httpGet).getEntity();
if (httpEntity != null){
InputStream inputStream = httpEntity.getContent();
Reader in = new InputStreamReader(inputStream);
BufferedReader bufferedreader = new BufferedReader(in);
StringBuilder stringBuilder = new StringBuilder();
String stringReadLine = null;
while ((stringReadLine = bufferedreader.readLine()) != null) {
stringBuilder.append(stringReadLine + "\n");
}
qResult = stringBuilder.toString();
inputStream.close();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return qResult;
}
private FlickrImage[] ParseJSON(String json){
FlickrImage[] flickrImage = null;
bmFlickr = null;
String flickrId;
String flickrOwner;
String flickrSecret;
String flickrServer;
String flickrFarm;
String flickrTitle;
try {
JSONObject JsonObject = new JSONObject(json);
JSONObject Json_photos = JsonObject.getJSONObject("photos");
JSONArray JsonArray_photo = Json_photos.getJSONArray("photo");
flickrImage = new FlickrImage[JsonArray_photo.length()];
for (int i = 0; i < JsonArray_photo.length(); i++){
JSONObject FlickrPhoto = JsonArray_photo.getJSONObject(i);
flickrId = FlickrPhoto.getString("id");
flickrOwner = FlickrPhoto.getString("owner");
flickrSecret = FlickrPhoto.getString("secret");
flickrServer = FlickrPhoto.getString("server");
flickrFarm = FlickrPhoto.getString("farm");
flickrTitle = FlickrPhoto.getString("title");
flickrImage[i] = new FlickrImage(flickrId, flickrOwner, flickrSecret,
flickrServer, flickrFarm, flickrTitle);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return flickrImage;
}
public class BackgroundThread extends Thread{
volatile boolean running = false;
int cnt;
void setRunning(boolean b){
running = b;
cnt = 10;
}
#Override
public void run() {
// TODO Auto-generated method stub
String searchQ = searchText.getText().toString();
String searchResult = QueryFlickr(searchQ);
myFlickrImage = ParseJSON(searchResult);
handler.sendMessage(handler.obtainMessage());
}
}
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
progressDialog.dismiss();
photoBar.setAdapter(new FlickrAdapter(AndroidFlickrActivity.this, myFlickrImage));
Toast.makeText(AndroidFlickrActivity.this,
"Images Loaded", Toast.LENGTH_LONG).show();
}
};
}
Write your activity so that it is aware of its current state.
In your onPause() method, save that state in any manner that you like. SharedPrefs, storage to a database, to a flat file, etc.
In your onResume() method, read that state and restore it.