This is the code I got from internet which I need it for my own application. I am trying to make an app using the example. The difference is that I made one separate class for this named JSONTask. I am getting error with getApplicationContex() function. Please help me with this.
import android.os.AsyncTask;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import navdrawerexample1.models.MovieModel;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class JSONTask extends AsyncTask<String,String,List<MovieModel>>
{
private ListView lvMovies;
#Override
protected List<MovieModel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url= new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line ="";
while ((line = reader.readLine())!=null){
buffer.append(line);
}
String finalJason = buffer.toString();
JSONObject parentObject = new JSONObject(finalJason);
JSONArray parentArray = parentObject.getJSONArray("movies");
List<MovieModel> movieModelList = new ArrayList<>();
//StringBuffer finalBufferData = new StringBuffer();
for (int i=0; i<parentArray.length();i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
MovieModel movieModel = new MovieModel();
movieModel.setMovie(finalObject.getString("movie"));
movieModel.setYear(finalObject.getInt("year"));
movieModel.setRating((float) finalObject.getDouble("rating"));
movieModel.setDuration(finalObject.getString("duration"));
movieModel.setDirector(finalObject.getString("director"));
movieModel.setTagline(finalObject.getString("tagline"));
movieModel.setImage(finalObject.getString("image"));
movieModel.setStory(finalObject.getString("story"));
List<MovieModel.cast> castList = new ArrayList<>();
for (int j=0; j<finalObject.getJSONArray("cast").length();j++){
MovieModel.cast cast = new MovieModel.cast();
cast.setName(finalObject.getJSONArray("cast").getJSONObject(j).getString("name"));
castList.add(cast);
}
movieModel.setCastList(castList);
//adding the final object in the list
movieModelList.add(movieModel);
}
return movieModelList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<MovieModel> result) {
super.onPostExecute(result);
//This is where I get the error
MovieAdapter adapter = new MovieAdapter(getApplicationContext(),R.layout.row,result);
lvMovies.setAdapter(adapter);
//TODO need to set data to the list
}
}
The trouble is that you are calling getApplicationContext() inside a Class that does not extend Context or its subclasses (Activity, etc). You should pass Context or its subclass to the JSONTask constructor. Furthermore, I don't see where you are initializing lvMovies - and you are likely to get NullPointerException at lvMovies.setAdapter(adapter); - my suggestion is that you should pass this as well to your JSONTask constructor:
private Context mContext;
private ListView lvMovies;
public JSONTask (Context context, ListView lstView){
this.lvMovies = lstView;
this.mContext = context;
}
so that in the onPostExecute you can do something like:
MovieAdapter adapter = new MovieAdapter(mContext,R.layout.row,result);
lvMovies.setAdapter(adapter);
I hope this helps.
First declare context,
Activity context;
then
MovieAdapter adapter = new MovieAdapter(context.getApplicationContext(),R.layout.row,result);
lvMovies.setAdapter(adapter);
I hope this is helpfull to you......
You cannot access getApplicationContext() from asynTask because getApplicationContext() doesn't exist in AsyncTask.
Make a constructor and pass Context to this class. Use it in your JSONTask class.
I would recommend you to use Volley library instead of AsyncTask.
create a constructor and pass it a Context variable like
public class JSONTask extends AsyncTask<String,String,List<MovieModel>>{
public Context mContext;
public JSONTask(Context context){
this.mContext = context;
}
.
.
.
now create JsonTask object from your activity/service as
JSONTask task = new JSONTask(getApplicationContext());
and now you can use mContext where you need to pass a context.
Related
This app is supposed to display movie's tittles fetched from an API into a RecyclerView. I know I am getting the data right because of logs I made on the movies Arraylist, but for some reason, I can't display the info. The app does not crash, it just shows an empty view. I do really appreciate your help.
Disclaimers: I am a newbie, and this solution might be quite simple for experienced people. I usually don't ask questions unless I can't solve the issue, actually this is my first question ever. I've been around this for a few days now and I can't find a way. I understand that this code might have more than one problem on it, and you are very welcome to point them all out.
SO, this is my main activity
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
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.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
public static final String LOG_TAG = MainActivity.class.getSimpleName();
private static final String MOST_POPULAR_MOVIES = "http://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=XXXXXXXXXXXXXXXXXXX";
ArrayList<Pelicula> ArrayDePeliculas;
private RecyclerView mPelisList;
private AdapterRV adapterRV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PeliculasAsyncTask task = new PeliculasAsyncTask();
task.execute(createUrl(MOST_POPULAR_MOVIES));
adapterRV = new AdapterRV(getApplicationContext(),/*Aca puede faltar algo*/ new ArrayList<Pelicula>());
mPelisList = findViewById(R.id.rv_pelis);
GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
mPelisList.setLayoutManager(layoutManager);
mPelisList.setAdapter(adapterRV);
}
public void updateUi(ArrayList<Pelicula> peliculas) {
}
/**
* 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;
}
/**
* Make an HTTP request to the given URL and return a String as the response.
*/
private String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
// If the URL is null, then return early.
if (url == null) {
return 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 the request was successful (response code 200),
// then read the input stream and parse the response.
if (urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} else {
Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
}
} catch (IOException e) {
Log.e(LOG_TAG, "Problem retrieving the earthquake JSON results.", e);
} 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();
}
/**
* TODO modificar la url que le estas pasando
*/
public ArrayList<Pelicula> extractFeatureFromJson(String jsonResponse) {
ArrayList<Pelicula> arraydePelis = new ArrayList<>();
try {
JSONObject baseJsonResponse = new JSONObject(jsonResponse);
JSONArray resultsArray = baseJsonResponse.getJSONArray("results");
for (int i = 0; i < resultsArray.length(); i++) {
// If there are results in the features array
if (resultsArray.length() > 0) {
// Extract out the first feature (which is an earthquake)
JSONObject firstResult = resultsArray.getJSONObject(i);
String tittle = firstResult.getString("title");
Pelicula pelicula = new Pelicula(tittle);
arraydePelis.add(pelicula);
}
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Problem parsing the earthquake JSON results", e);
}
return arraydePelis;
}
private class PeliculasAsyncTask extends AsyncTask<URL, Void, ArrayList<Pelicula>> {
#Override
protected ArrayList<Pelicula> doInBackground(URL... urls) {
// Create URL object
URL url = createUrl(MOST_POPULAR_MOVIES);
// Perform HTTP request to the URL and receive a JSON response back
String jsonResponse = "";
try {
jsonResponse = makeHttpRequest(url);
} catch (IOException e) {
Log.e(LOG_TAG, "Problem making the HTTP request.", e);
}
// Extract relevant fields from the JSON response and create an {#link Event} object
ArrayList<Pelicula> ArrayPeliculas = extractFeatureFromJson(jsonResponse);
// Return the {#link Event} object as the result fo the {#link TsunamiAsyncTask}
return ArrayPeliculas;
}
#Override
protected void onPostExecute(ArrayList<Pelicula> data) {
if (data == null) {
return;
}
adapterRV.notifyDataSetChanged();
mPelisList.setAdapter(adapterRV);
Log.e("Nada", data.get(6).getTittle());
super.onPostExecute(data);
}
}
}
The Movie class
public class Pelicula {
//Fields
private String mTittle;
//Constructor
public Pelicula(String Tittle){
mTittle= Tittle;
}
//Methods
public String getTittle (){
return mTittle;
}
}
And finally, the recyclerView adapter
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class AdapterRV extends RecyclerView.Adapter<AdapterRV.PelisViewHolder> {
//Fields
List<Pelicula> mPeliculas;
private Context context;
/* TODO, comprobar que no necesitas esto: mNumberItems = numberOfItems; y poner autofit en grid view */
//Constructor
public AdapterRV (Context context, ArrayList<Pelicula> peliculas){
mPeliculas = peliculas;
this.context= context;
}
//Metodos
#NonNull
#Override
public PelisViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
Context context = parent.getContext();
int layoutForListItem = R.layout.item_layout;
LayoutInflater inflater= LayoutInflater.from(context);
View view = inflater.inflate(layoutForListItem, parent, false);
PelisViewHolder viewHolder = new PelisViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull PelisViewHolder holder, int position) {
Pelicula peliculas = mPeliculas.get(position);
TextView textView = holder.listItemTittleView;
textView.setText(peliculas.getTittle());
}
#Override
public int getItemCount() {
return mPeliculas.size();
}
public class PelisViewHolder extends RecyclerView.ViewHolder{
TextView listItemTittleView;
public PelisViewHolder(#NonNull View itemView) {
super(itemView);
listItemTittleView = itemView.findViewById(R.id.tv_title);
}
}
}
The problem is that you are passing new ArrayList<Pelicula>() to your adapter, and this list is remaining empty. I suggest you declare a global reference of Pelicula list inside your MainActivity and then pass it to the adapter. Whenever that list changes, then notifyDataSetChanged.
If you don't want to declare a global reference, just declare a method inside your adapter:
public void setList(ArrayList list){
this.list = list;
}
and in your MainActivity, just everything you get a new list, setList(newPeliculaList) and adapterRV.notifyDataSetChanged()
Edit:
in onCreate() before declaring the AdapterRV:
just put this:
ArrayDePeliculas = new ArrayList<Pelicula>();
Do you see these 2 lines in onCreate()
adapterRV = new AdapterRV(getApplicationContext(),new ArrayList<Pelicula>());
...
...
mPelisList.setAdapter(adapterRV);
Move them to onPostExecute() of the asyncTask and pass the data instead of a new ArrayList<Pelicula>():
#Override
protected void onPostExecute(ArrayList<Pelicula> data) {
//assuming the list is full and all is good
if (data == null) {
return;
}
//here...
adapterRV = new AdapterRV(getApplicationContext(),data);
mPelisList.setAdapter(adapterRV);
Log.e("Nada", data.get(6).getTittle());
super.onPostExecute(data);
}
UPDATE:
Its because you don't initialize the list in the adapter:
public class AdapterRV extends RecyclerView.Adapter<AdapterRV.PelisViewHolder> {
//Fields
//here you must initialize like this:
List<Pelicula> mPeliculas = new ArrayList<Pelicula>();
.....
I'm working on udacity popular movies stage 1 project that will allow me to discover movies from themoviedb database.
I've created Movie, MovieAdapter, and MainActivity(with FetchMovieAsyncTask as inner class) classes. But I keep getting below error
java.lang.NullPointerException: Attempt to invoke interface method
'int java.util.List.size()' on a null object reference
These are my codes
Movie class:
public class Movie{
private String mMovieTitle;
private String mPosterPath;
private String mOverview;
private String mReleaseDate;
private double mRating;
public Movie(){
mMovieTitle = null;
mPosterPath = null;
mOverview = null;
mReleaseDate = null;
mRating = -1.0;
}
public Movie(String title){
mMovieTitle = title;
}
public Movie(String title, String posterPath, String overview, String releaseDate, double rating){
mMovieTitle = title;
mPosterPath = posterPath;
mOverview = overview;
mReleaseDate = releaseDate;
mRating = rating;
}
public String getMovieTitle(){
return mMovieTitle;
}
public String getPosterPath(){
return mPosterPath;
}
public String getOverview(){
return mOverview;
}
public String getReleaseData(){
return mReleaseDate;
}
public double getRating(){
return mRating;
}
}
MovieAdapter class:
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
/**
* Created by ibayp on 04/08/2017.
*/
public class MovieAdapter extends ArrayAdapter<Movie> {
Context context;
ArrayList<Movie> movies;
public MovieAdapter(Context context, ArrayList<Movie> movies){
super(context, 0, movies);
this.context = context;
this.movies = movies;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View view = convertView;
if(view == null){
view = LayoutInflater.from(getContext()).inflate(R.layout.poster_list, parent, false);
}
ImageView imageView = (ImageView)view.findViewById(R.id.movie_poster);
Picasso.with(getContext())
.load("https://image.tmdb.org/t/p/w500/kqjL17yufvn9OVLyXYpvtyrFfak.jpg")
.into(imageView);
return view;
}
}
and MainActivity class:
package com.android.ibayp.popularmovies;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
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.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
GridView gridView;
ArrayList<Movie> movies;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new FetchMovieAsyncTask().execute("popularity.desc");
MovieAdapter adapter = new MovieAdapter(this, movies);
gridView = (GridView)findViewById(R.id.grid_view);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long l) {
Movie movie = (Movie)parent.getItemAtPosition(position);
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
intent.putExtra("title", movie.getMovieTitle());
startActivity(intent);
}
});
}
private class FetchMovieAsyncTask extends AsyncTask<String, Void, ArrayList<Movie>> {
private final String TAG = com.android.ibayp.popularmovies.FetchMovieAsyncTask.class.getSimpleName();
private static final String API_KEY = "api key";
private static final String BASE_URL = "https://api.themoviedb.org/3/discover/movie?";
private String API_PARAM = "api_key";
private String SORT_BY = "sort_by";
public URL buildURL(String[] sortMethod){
Uri builtUri = Uri.parse(BASE_URL).buildUpon()
.appendQueryParameter(API_PARAM, API_KEY)
.appendQueryParameter(SORT_BY, sortMethod[0])
.build();
URL url = null;
try{
url = new URL(builtUri.toString());
}catch (MalformedURLException e){
e.printStackTrace();
}
Log.v(TAG, "BUILT URI: " +url);
return url;
}
private String makeHttpRequst(URL url)throws IOException {
String jsonResponse = "";
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try{
urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
inputStream = urlConnection.getInputStream();
jsonResponse = readStream(inputStream);
}catch (IOException e){
e.printStackTrace();
}finally {
if(urlConnection!=null){
urlConnection.disconnect();
}
if (inputStream!=null){
inputStream.close();
}
}
return jsonResponse;
}
private String readStream(InputStream inputStream) throws IOException{
StringBuilder results = 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){
results.append(line);
line = reader.readLine();
}
}
return results.toString();
}
private ArrayList<Movie> getMovieFromJson(String movieJson){
movies = new ArrayList<Movie>();
try{
JSONObject baseResponse = new JSONObject(movieJson);
JSONArray resultsArray = baseResponse.getJSONArray("results");
Log.v(TAG, "Array Results: "+resultsArray.length());
if (resultsArray.length() > 0){
for (int i = 0; i<resultsArray.length(); i++ ){
JSONObject movieInformation = resultsArray.getJSONObject(i);
movies.add(new Movie(movieInformation.getString("title"),
movieInformation.getString("poster_path"),
movieInformation.getString("overview"),
movieInformation.getString("release_date"),
movieInformation.getDouble("vote_average")));
}
}
}catch (JSONException e){
Log.v(TAG, "Problem parsing Json" + e);
}
return movies;
}
#Override
protected ArrayList<Movie> doInBackground(String... strings) {
URL url = buildURL(strings);
String jsonResponse = "";
try{
jsonResponse = makeHttpRequst(url);
}catch (IOException e){
Log.v(TAG, "IO Exception error "+e);
}
movies = getMovieFromJson(jsonResponse);
return movies;
}
#Override
protected void onPostExecute(ArrayList<Movie> movies) {
if (movies==null){
return;
}
super.onPostExecute(movies);
}
}
}
I used logging and managed to get the correct json results, but I can't display it on the ui thread.
How can I solve this? Thanks
*note that I used dummy image for the poster
When you instantiate your adapter movies are null. Because asynctask is running in parallel thread. Instantiate your adapter in your asynctask's onPostExecute method. This way you will be sure asynctask is completed.
#Override
protected void onPostExecute(ArrayList<Movie> movies) {
if (movies==null){
return;
}
super.onPostExecute(movies);
MovieAdapter adapter = new MovieAdapter(MainActivity.this, movies);
gridView.setAdapter(adapter);
}
Call adapter.notifyDataSetChanged() after movies.add(...) or in onPostExecute
I finished the Android Nanodegree a while back and remember working on this project. When you instantiate an adapter it will call the getSize() method to determine how many rows to create for the views and then call getView() on each of them to bind the views.
Since your async Task may not have finished downloading the movies, you're passing an empty list to the adapter and thus getting a NullPointerException.
It's always a good approach to instantiate the adapter in the onPostExecute() method of AsyncTask. This method is called on the UI thread after the background thread has finished execution.
So put these two lines of code in onPostExecute() and it should work
MovieAdapter adapter = new MovieAdapter(MainActivity.this, movies);
gridView.setAdapter(adapter);
I'm developing an app and now I have to pass a parameter to a RESTful Service's URL. I'm using AsyncTask, and I need to pass a text from a list view as a parameter to the URL, for example: the URL is http://ip:7001/product?product_name=PARAM I need to get the text from the selected item from my list view, and pass as a parameter in PARAM, using AsyncTask. I've already got the text from the item in the listView, now I just need to pass it as a parameter.
This is my AsycTask class:
package com.tumta.henrique.teste;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import com.tumta.henrique.teste.ProdutoFragment;
/**
* Created by Henrique on 18/05/2015.
*/
public class FiltraProduto extends AsyncTask<String, Void, List<String>> {
private ConsultaConcluidaFiltroProdutoListener listener;
public static String URL_STRING = "http://192.168.0.20:7001/com.henrique.rest/api/v1/status/pro_filtro?pro_nome=";
public FiltraProduto(ConsultaConcluidaFiltroProdutoListener listener) {
this.listener = listener;
}
private List<String> InterpretaResultado(String resultado) throws JSONException {
JSONObject object = new JSONObject(resultado);
JSONArray jsonArray = object.getJSONArray("produto");
//JSONObject jsonProduto = jsonArray.getJSONObject(0);
// String id = jsonProduto.getString("pro_id");
//proId = id;
List<Object> listaNomes = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonProdutoInfo = jsonArray.getJSONObject(i);
String proNome= jsonProdutoInfo.getString("pro_nome");
double proPreco = jsonProdutoInfo.getDouble("pro_preco");
double proSdAtual = jsonProdutoInfo.getDouble("pro_sdAtual");
listaNomes.add(i, proNome);
listaNomes.add(i, proPreco);
listaNomes.add(i, proSdAtual);
}
List<String> strings = new ArrayList<String>();
for (Object o : listaNomes) {
strings.add(o != null ? o.toString() : null);
}
return strings;
}
private String ConsultaServidor() throws IOException {
InputStream is = null;
try {
URL url = new URL(URL_STRING);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(10000);
conn.setReadTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
conn.getResponseCode();
is = conn.getInputStream();
Reader reader = null;
reader = new InputStreamReader(is);
char[] buffer = new char[2048];
reader.read(buffer);
return new String(buffer);
} finally {
if (is != null) {
is.close();
}
}
}
#Override
protected List<String> doInBackground(String... params) {
try {
String resultado = ConsultaServidor();
return InterpretaResultado(resultado);
} 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(List<String> result) {
listener.onConsultaConcluida(result);
super.onPostExecute(result);
}
public interface ConsultaConcluidaFiltroProdutoListener {
void onConsultaConcluida(List<String> result);
}
}
In the URL_STRING I need to pass the param at pro_nome=?
Here I get the item text. This is in my Fragment that has the List View:
public String retornaParam(String param){
return param;
}
#Override
public void onConsultaConcluida(List<String> result) {
final ListView listaProdutos = (ListView) getView().findViewById(R.id.listaprodutos);
ArrayAdapter arrayAdapter = new ArrayAdapter<>(getView().getContext(),android.R.layout.simple_list_item_1, result);
listaProdutos.setAdapter(arrayAdapter);
listaProdutos.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parentAdapter, View view, int position,
long id) {
String nomeProduto = listaProdutos.getItemAtPosition(position).toString();
retornaParam(nomeProduto);
Intent intent = new Intent(getActivity(), DetalhesProdutoActivity.class);
//intent.putExtra("pro_nome", listaProdutos.getItemAtPosition(position).toString());
startActivity(intent);
}
});
}
I get the text and store it in param from the retornaParam method.
Does somebody know how to do it?
If you need more information, just let me know.
You pass in params to an AsyncTask using:
YourAsyncTask.execute(yourview.getText(), "and", "more", "params");
You can then access them in
#Override
protected String doInBackground(String... params) {
URL_STRING += params[0];
...
Just add the following code before sending executing your httpClient:
URL_STRING + = textInsideYourTextView;
It should work, just avoid to manipulate your ui elements outside your UI thread.
I'm new to android and I hope someone could help me here. I have an activity Faculty and a button.
This is my XML layout browse_faculty:
<Button
android:onClick="searchFSTEHandler"
android:id="#+id/bFSTE"
android:layout_width="220dp"
android:layout_height="80dp"
android:layout_alignLeft="#+id/bFBE"
android:layout_below="#+id/bFBE"
android:layout_marginTop="20dp"
android:text="#string/fste" />
and this is my Faculty Activity which displays the buttons:
I use Intent to view ListView
public class Faculty extends Activity{
#Override
protected void onCreate(Bundle BrowseFaculty) {
// TODO Auto-generated method stub
super.onCreate(BrowseFaculty);
setContentView(R.layout.browse_faculty);
}
//on the XML,this is the "searchFSTEHandler" i want to use to show ListView
public void searchFSTEHandler(View target){
Intent courseList = new Intent(this, HttpActivity.class);
startActivity(courseList);
}
}
and below is the "HttpActivity" class is the class that displays my ListView. This class read a php file which gets data from a MySQL server and converts to JSON data then parses it into a array list.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.ListActivity;
import android.widget.ArrayAdapter;
public class HttpActivity extends ListActivity {
public String f1 = "FSTE";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.faculty_course);
new getHttp().execute();
getHttp test =new getHttp();
String strJsonData = test.doInBackground(f1);
// Convert String JSON data to Java class
ArrayList<Courses> arrayCourse= test.parseJsonData(strJsonData);
//Create an ArrayAdapter which shows the ArrayList data
this.setListAdapter(new ArrayAdapter<Courses>(this,android.R.layout.simple_list_item_1,arrayCourse));
}
private class getHttp extends AsyncTask<String, Void, String> {
public getHttp() {
}
#Override
protected String doInBackground(String... faculty) {
InputStream is = null;
try {
URL url = new URL("http://10.0.2.2/sqlWebService.php?faculty=FSTE");
URLConnection con = url.openConnection();
con.setConnectTimeout(10000);
con.setReadTimeout(10000);
is = con.getInputStream();
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
StringBuffer sb = new StringBuffer();
String str;
while ((str = br.readLine()) != null) {
sb.append(str);
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
return "";
} finally {
try {
if (is != null)
is.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
//------------------------------------------------------
private ArrayList<Courses> parseJsonData(String strJson) {
ArrayList<Courses> Course = new ArrayList<Courses>();
try {
// Generate JSONArray object by JSON String data
JSONArray arr = new JSONArray(strJson);
//from the JSONArray, get one element (row) of JSONData
for (int i = 0; i < arr.length(); i++) {
//Get JSON Object which is one element of the array
JSONObject ob = arr.getJSONObject(i);
Courses exam = new Courses();
//get the value by key, and set to exam class
exam.setCode(ob.optString("code"));
//save exam class to exam array list
Course.add(exam);
}
} catch (JSONException e) {
e.printStackTrace();
}
return Course;
}
}
}
The application crashes as soon as I click on the button and gives a error:
"android.os.NetworkOnMainThreadException"
Help Please !
The problem that you are having is network operation like what you are trying to do cannot and should not be performed on the main UI thread. Doing so will lead to an ANR (Android Not Responding), which is exactly the kind of error you are getting just now. What you want to do is move your code to a separate thread or to an AsyncTask that will perform this action in the background on a different thread using the doInBackground() method which does not have access to your views on the main UI thread. For example,
private class ExampleOperation extends AsyncTask<String, Void, String> {
public ExampleOperation() { //ctor }
#Override
protected void onPreExecute() {
//things that you want to initialize and maybe show dialog to user.
}
#Override
protected String doInBackground(String... params) {
//this is where you perform that network related operation.
}
#Override
protected void onPostExecute(String result) {
//this is where get the results from the network related task.
}
#Override
protected void onProgressUpdate(Void... values) {
//you can update your progressbar if any; otherwise omit method.
}
}
Then all you have to do is call the AsyncTask where ever you want to use it: new ExampleOperation().execute();
You can't make HTTP calls in the main thread, they take too long and would make the UI unresponsive. You need to do it in an AsyncTask.
This is probably not very elegant, but what I'm trying to do is connect to a web service, fetch the JSON, parse it, create an object out of it, add that object to an ArrayList and then use that ArrayList to populate my ListView.
I'm trying to do all of this with AsyncTask.
SUMMARY: doInBackgroud takes a String of a url, uses it to connect to a web service. I get the JSON data as a string, parse it, construct a new object out of the data, and add it to ArrayList. Then in onPostExecute I'm trying to set the listadapter using an ArrayAdapter that utilizes my ArrayList.
Here's what I have:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import org.json.JSONArray;
import org.json.JSONObject;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.basic.DefaultOAuthConsumer;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ArrayAdapter;
public class AllOffersListActivity extends ListActivity {
private static final String CONSUMER_KEY = "bla";
private static final String CONSUMER_SECRET = "bla";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new CreateArrayListTask().execute("http://example.com/sample.json");
}
private class CreateArrayListTask extends AsyncTask<String, Void, ArrayList<Offer>> {
private final ProgressDialog dialog = new ProgressDialog(AllOffersListActivity.this);
#Override
protected void onPreExecute() {
this.dialog.setMessage("Fetching offers...");
this.dialog.show();
}
#Override
protected ArrayList<Offer> doInBackGround(String...urls) {
ArrayList<Offer> offerList = new ArrayList<Offer>();
for(String url: urls) {
OAuthConsumer consumer = new DefaultOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
consumer.setTokenWithSecret("", "");
try {
URL url1 = new URL(url);
HttpURLConnection request = (HttpURLConnection) url1.openConnection();
// sign the request
consumer.sign(request);
// send the request
request.connect();
String JSONString = convertStreamToString(request.getInputStream());
JSONObject jObject = new JSONObject(JSONString);
JSONObject offerObject = jObject.getJSONObject("offer");
String titleValue = offerObject.getString("title");
//System.out.println(titleValue);
String descriptionValue = offerObject.getString("description");
//System.out.println(attributeValue);
JSONObject businessObject = offerObject.getJSONObject("business");
String nameValue = businessObject.getString("name");
Offer myOffer = new Offer(titleValue, descriptionValue, nameValue);
offerList.add(myOffer);
} catch (Exception e) {
e.printStackTrace();
}
}
return offerList;
}
#Override
protected void onPostExecute(ArrayList<Offer> offerList) {
if(this.dialog.isShowing())
this.dialog.dismiss();
setListAdapter(new ArrayAdapter<Offer>(AllOffersListActivity.this, android.R.layout.simple_list_item_1, offerList));
}
}
private String convertStreamToString(InputStream inputStream) throws IOException {
if(inputStream != null) {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader( new InputStreamReader(inputStream, "UTF-8"));
int n;
while((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
inputStream.close();
}
return writer.toString();
} else {
return "";
}
}
}
I'm seeing two errors. One is on my private Async class: "The type AllOffersListActivity.CreateArrayListTask must implement the inherited abstract method AsyncTask<String,Void,ArrayList<Offer>>.doInBackground(String...)"
Secondly, on my doInBackGround Override, I'm getting: The method doInBackGround(String...) of type AllOffersListActivity.CreateArrayListTask must override or implement a supertype method
What am I missing here?
It's just a small typo; should be doInBackground instead of doInBackGround.
#LuxuryMode you have done mistake on doInBackGround
the correct spelling is doInBackground
asynctask must have to implement doInBackground method so it is not recognize this method because of wrong Name of method so it gives you error
The method doInBackGround(String...) of type AllOffersListActivity.CreateArrayListTask must
override or implement a supertype method