I have an app I am trying to pass data through an ASYNC task but am getting a null pointer error in my onPosteExecute method. Seems like no matter how I change my code I still get this same fatal error:
10-31 18:43:56.517 1253-1253/com.brianstacks.project1 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.brianstacks.project1, PID: 1253
java.lang.NullPointerException
at com.brianstacks.project1.MainActivity$MyTask.onPostExecute(MainActivity.java:277)
at com.brianstacks.project1.MainActivity$MyTask.onPostExecute(MainActivity.java:247)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Here is my code:
MainActivity.java
public class MainActivity extends ListActivity implements MasterFragment.OnListItemClickListener {
final String Tag = "Project 1 test";
EditText myEdit;
Button myButton;
ProgressBar pb;
SerialCustomObject myObject;
// create a reference to the list's needed for data
List<MyTask> tasks;
ArrayList<Places> placeList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if ((savedInstanceState != null)&& (savedInstanceState.getSerializable("name") != null)) {
Places name = (Places) savedInstanceState.getSerializable("name");
Log.v("name:",name.getName());
}
//initiate my tasks
tasks = new ArrayList<>();
pb = (ProgressBar)findViewById(R.id.progressBar);
myEdit = (EditText)findViewById(R.id.myEditText);
myButton = (Button)findViewById(R.id.myButton);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
return id == R.id.action_settings || super.onOptionsItemSelected(item);
}
public void findAndRemoveFragment() {
FragmentManager mgr = getFragmentManager();
DetailFragment frag =
(DetailFragment) mgr.findFragmentByTag(DetailFragment.TAG);
if (frag == null) {
// No fragment found, possibly because the transaction
// hasn't completed yet.
} else {
// Fragment found. You can use it here.
FragmentTransaction trans = mgr.beginTransaction();
trans.remove(frag);
trans.commit();
// When the main thread runs, the fragment will be
// removed from the activity.
}
}
public void deviceStorage() {
// Read in a private file
try {
FileInputStream fis = this.openFileInput("some_file.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// Create new or open existing private file
try {
FileOutputStream fos = this.openFileOutput("some_other_file.txt", Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private void writeToFile(Context _c, String _filename, String _data) {
File external = _c.getExternalFilesDir(null);
File file = new File(external, _filename);
try {
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
if(myObject == null) {
myObject = new SerialCustomObject();
}
myObject.setData(_data);
oos.writeObject(myObject);
oos.close();
// Write bytes to the stream
fos.write(_data.getBytes());
// Close the stream to save the file.
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private String readFromFile(String _filename) {
File external = getExternalFilesDir(null);
File file = new File(external, _filename);
try {
FileInputStream fin = new FileInputStream(file);
InputStreamReader inReader = new InputStreamReader(fin);
BufferedReader reader = new BufferedReader(inReader);
// Reading data from our file using the reader
// and storing it our string buffer.
StringBuffer buffer = new StringBuffer();
String text = null;
// Make sure a line of text is available to be read.
while((text = reader.readLine()) != null) {
buffer.append(text + "\n");
}
// Close the reader and underlying stream.
reader.close();
// Convert the buffer to a string.
return buffer.toString();
} catch(IOException e) {
e.printStackTrace();
}
return null;
}
#Override
public void displayText(String myText) {
DetailFragment frag = (DetailFragment) getFragmentManager().findFragmentByTag(DetailFragment.TAG);
if (frag == null){
frag = DetailFragment.newInstance(myText);
getFragmentManager().beginTransaction()
.replace(R.id.container2,frag,DetailFragment.TAG)
.commit();
}else {
frag.setDisplayInfo(myText);
}
}
//#Override
public void onClick(View _v){
myEdit = (EditText)findViewById(R.id.myEditText);
String newString = myEdit.getText().toString();
Log.v(Tag,newString);
}
// the method for when the button is clicked
public void myClick(View _v){
// create a string to grab the text of the edit text
String myString = myEdit.getText().toString();
// replace the spaces with + to encode into the url
String encodedString = myString.replace(" ","+");
//check to see if online and if so continue to get the JSON data if not toast a message telling the user no connection
if (isOnline()){
requestData("https://maps.googleapis.com/maps/api/place/textsearch/json?query="+encodedString+"&key=AIzaSyB9iOw6wF4FwbOdUTZYiU_MxsbfWM5iMOI");
}else Toast.makeText(this, "Network isn't available", Toast.LENGTH_SHORT).show();
}
// method to get the data from ASYNC task
private void requestData(String uri) {
MyTask task = new MyTask();
task.execute(uri);
}
// method to check internet connectivity
protected boolean isOnline(){
ConnectivityManager cm =(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
protected void updateDisplay(ArrayList<Places> placeList){
// get instance of the Master List fragment then replaces container1 and commits it to the activity
MasterFragment frag = MasterFragment.newInstance(placeList);
getFragmentManager().beginTransaction()
.replace(R.id.container1, frag, MasterFragment.TAG).commit();
}
// Async task method to do network action in
private class MyTask extends AsyncTask<String ,String ,String>{
#Override
protected void onPreExecute() {
// add this to the task
tasks.add(this);
}
#Override
protected String doInBackground(String... params) {
return HttpManager.getData(params[0]);
}
#Override
protected void onPostExecute(String result) {
tasks.remove(this);
if(null != result && !result.isEmpty()) {
placeList = JSONParser.parseFeed(result);
updateDisplay(placeList);
}else {
Toast.makeText(MainActivity.this, "Can't connect to API", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onProgressUpdate(String... values) {
}
}
}
DetailFragment.java
package com.brianstacks.project1.fragments;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.brianstacks.project1.R;
/**
* Created by Brian Stacks
* on 10/27/14
* for FullSail.edu.
*/
public class DetailFragment extends Fragment {
public static final String TAG = "DetailFragment.TAG";
public static final String ARG_TAG = "DetailFragment.TAG";
public static DetailFragment newInstance(String myString) {
DetailFragment frag = new DetailFragment();
Bundle args = new Bundle();
args.putString(ARG_TAG, myString);
frag.setArguments(args);
return frag;
}
#Override
public View onCreateView(LayoutInflater _inflater, ViewGroup _container,
Bundle _savedInstanceState) {
// Create and return view for this fragment.
return _inflater.inflate(R.layout.detail_layout, _container, false);
}
#Override
public void onActivityCreated(Bundle _savedInstanceState) {
super.onActivityCreated(_savedInstanceState);
Bundle args = getArguments();
if(args != null && args.containsKey(ARG_TAG)){
setDisplayInfo(args.getString(ARG_TAG));
}
}
public void setDisplayInfo(String myText){
getArguments().putString(ARG_TAG,myText);
// Get our TextView and set some text to it.
TextView tv;
tv = (TextView)getView().findViewById(R.id.detailText);
tv.setText(myText);
}
}
MasterFragment.java
package com.brianstacks.project1.fragments;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListFragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.brianstacks.project1.JSONParser;
import com.brianstacks.project1.MainActivity;
import com.brianstacks.project1.Places;
import com.brianstacks.project1.PlacesAdapter;
import com.brianstacks.project1.R;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Brian Stacks
* on 10/27/14
* for FullSail.edu.
*/
public class MasterFragment extends ListFragment{
public static final String TAG = "MasterFragment.TAG";
public static final String KEY = "places";
private OnListItemClickListener mListener;
private ArrayList<Places> placeList2;
public static MasterFragment newInstance(ArrayList<Places> placeList) {
MasterFragment masterFragment = new MasterFragment();
Bundle args = new Bundle();
args.putSerializable("places", placeList);
masterFragment.setArguments(args);
return masterFragment;
}
public interface OnListItemClickListener{
public void displayText(String myText);
}
#Override
public void onAttach(Activity activity){
super.onAttach(activity);
if (activity instanceof OnListItemClickListener){
mListener = (OnListItemClickListener) activity;
}else {
throw new IllegalArgumentException("Containing Activity must implement the OnListItemClicked");
}
}
#Override
public void onActivityCreated(Bundle _savedInstanceState) {
super.onActivityCreated(_savedInstanceState);
if (_savedInstanceState == null){
Bundle args = getArguments();
String myStrings=args.getString("places");
Log.v("Places",myStrings);
/*String[] presidents = getResources().getStringArray(R.array.presidents);
//ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, presidents);
//PlacesAdapter adapter2 = new PlacesAdapter(this.getActivity(),R.layout.item_place,placeList);
//setListAdapter(adapter2);
}
#Override
public void onListItemClick(ListView _l, View _v, int _position, long _id) {
String president = (String)_l.getItemAtPosition(_position);
mListener.displayText(president);
*/
}
}
}
HTTPManager.java
package com.brianstacks.project1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by Brian Stacks
* on 10/20/14
* for FullSail.edu.
*/
public class HttpManager {
public static String getData(String uri){
BufferedReader reader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = reader.readLine()) != null){
sb.append(line).append("");
}
return sb.toString();
}catch (Exception e){
e.printStackTrace();
return null;
}finally {
if (reader!=null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
JSONParser.java
package com.brianstacks.project1;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Brian Stacks
* on 10/20/14
* for FullSail.edu.
*/
public class JSONParser {
public static ArrayList<Places> parseFeed(String content) {
JSONObject myObj;
try {
myObj = new JSONObject(content);
JSONArray result = myObj.getJSONArray("results");
ArrayList<Places> placeList = new ArrayList<>();
for (int i = 0; i < result.length(); i++) {
JSONObject obj = result.getJSONObject(i);
Places place = new Places();
place.setName(obj.getString("name"));
place.setFormatted_address(obj.getString("formatted_address"));
place.setTypes(obj.getString("types"));
//place.setPhotos(obj.getString("photos"));
placeList.add(place);
}
return placeList;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
}
Places.java
import java.io.Serializable;
/**
* Created by Brian Stacks
* on 10/22/14
* for FullSail.edu.
*/
public class Places implements Serializable {
private String pName;
private String pTypes;
private String pFormatted_address;
public Places(){
pName ="";
pTypes ="";
pFormatted_address = "";
}
public String getName() {
return pName;
}
public void setName(String name) {
pName = name;
}
public String getTypes() {
return pTypes;
}
public void setTypes(String types) {
pTypes= types;
}
public String getFormatted_address() {
return pFormatted_address;
}
public void setFormatted_address(String formatted_address) {
pFormatted_address=formatted_address;
}
}
Any help is much appreciated
ALSO was reading this post but to no avail LINK!
I found my solution to this problem, it was I was trying to cast my Objectin my MasterFragment.java as a String when the code was expecting an ArrayList<Places> changed that bit of code and pow there it was, no error.
Old Code
Bundle args = getArguments();
String myStrings=args.getString("places");
New Code
Bundle args = getArguments();
ArrayList myStrings = args.getParcelableArrayList("places");
Related
I have a news app. My app takes so much time to fetch data from server and display it on the listView.But i have seen that apps like flipboard,facebook and Game News which has more data to fetch than mine does it faster.I think my app loads the entire data and displays the entire list together.Is there a way to display the list such that it loads the items in listView one by one?I do the fetching using a AsyncTaskLoader in the background.Also how to display a large list of news like 100 in a list .
MainActivity:
package com.example.android.gametalks;
import android.app.LoaderManager;
import android.content.Intent;
import android.content.Loader;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<GameNews>> {
//IGN url
final String ign_url = "https://newsapi.org/v1/articles?source=ign&sortBy=top&apiKey=679f6fb918d34343b18590ca70f7fcde";
final String google_url = " https://newsapi.org/v1/articles?source=google-news&sortBy=top&apiKey=679f6fb918d34343b18590ca70f7fcde";
final String engadget_url = "https://newsapi.org/v1/articles?source=engadget&sortBy=top&apiKey=679f6fb918d34343b18590ca70f7fcde";
GameAdapter adapter ;
private View progressBar;
final private int game_loader = 0;
ArrayList<String> urls = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
urls.add(ign_url);
urls.add(google_url);
urls.add(engadget_url);
//Getting listView
ListView gameListView = (ListView) findViewById(R.id.listView);
//progress bar finding
progressBar = findViewById(R.id.progress_bar);
ArrayList<GameNews> gameList = new ArrayList<>();
//Making a new arrayAdapter
adapter = new GameAdapter(this,gameList);
//Connecting ArrayAdapter to ListView
gameListView.setAdapter(adapter);
getLoaderManager().initLoader(game_loader, null, this);
//ListView item click listner
gameListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
GameNews currentEarthquake = adapter.getItem(i);
String url = currentEarthquake.getUrl();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
}
});
}
#Override
public Loader<List<GameNews>> onCreateLoader(int i, Bundle bundle) {
return new GameLoader(this,urls);
}
#Override
public void onLoadFinished(Loader<List<GameNews>> loader, List<GameNews> games) {
progressBar.setVisibility(View.INVISIBLE);
adapter.clear();
if(games == null)
{
return;
}
adapter.addAll(games);
}
#Override
public void onLoaderReset(Loader<List<GameNews>> loader) {
adapter.clear();
}
}
GameLoader:
package com.example.android.gametalks;
import android.content.AsyncTaskLoader;
import android.content.Context;
import java.util.ArrayList;
import java.util.List;
/**
* Created by apple on 9/8/17.
*/
public class GameLoader extends AsyncTaskLoader<List<GameNews>> {
private ArrayList<String> Urls = new ArrayList<>();
public GameLoader(Context context, ArrayList<String> Url) {
super(context);
Urls = Url;
}
#Override
protected void onStartLoading()
{
forceLoad();
}
#Override
public List<GameNews> loadInBackground() {
if(Urls == null)
{
return null;
}
// Perform the HTTP request for earthquake data and process the response.
List<GameNews> games = QueryUtils.FetchEarthquakeData(Urls);
return games;
}
}
QueryUtils(Here the network fetching takes place):
package com.example.android.gametalks;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.widget.ListView;
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.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Helper methods related to requesting and receiving earthquake data from USGS.
*/
public final class QueryUtils {
private static final String LOG_TAG = QueryUtils.class.getSimpleName();
/**
* Create a private constructor because no one should ever create a {#link QueryUtils} object.
* This class is only meant to hold static variables and methods, which can be accessed
* directly from the class name QueryUtils (and an object instance of QueryUtils is not needed).
*/
private QueryUtils() {
}
public static List<GameNews> FetchEarthquakeData(ArrayList<String> Url) {
List<GameNews> games ;
List<GameNews> Total = new ArrayList<>();
URL url;
Log.d(LOG_TAG,Url.get(0));
for(int i = 0 ; i < Url.size(); i++) {
url = createUrl(Url.get(i));
try {
//Make http request
String jsonResponse = makeHttpRequest(url);
games = extractFeatureFromJson(jsonResponse);
Total.addAll(games);
} catch (IOException e) {
Log.e("IOException", "" + e);
}
}
return Total;
}
private static URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error with creating URL ", e);
}
return url;
}
private static String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
InputStream inputStream = null;
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
if (urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readInputStream(inputStream);
} else {
Log.e(LOG_TAG, "" + urlConnection.getResponseCode());
return null;
}
} catch (IOException e) {
Log.d(LOG_TAG, "" + e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
// function must handle java.io.IOException here
inputStream.close();
}
}
return jsonResponse;
}
private static String readInputStream(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();
}
private static ArrayList<GameNews> extractFeatureFromJson(String jsonResponse) {
ArrayList<GameNews> games = new ArrayList<>();
try {
JSONObject jsonObject = new JSONObject(jsonResponse);
JSONArray articles = jsonObject.getJSONArray("articles");
for (int i = 0; i < articles.length(); i++) {
JSONObject currentGame = articles.getJSONObject(i);
// Extract the value for the key called "mag"
String title = currentGame.getString("title");
// Extract the value for the key called "place"
String description = currentGame.getString("description");
// Extract the value for the key called "url"
String url = currentGame.getString("url");
//Extract value from key called urlToImage
String urlToImage = "nn";
urlToImage = currentGame.getString("urlToImage");
URL urlOfImage = null;
Bitmap bmp = null;
try {
urlOfImage = new URL(urlToImage);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
bmp = BitmapFactory.decodeStream(urlOfImage.openConnection().getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
// Create a new {#link Earthquake} object with the magnitude, location, time,
// and url from the JSON response.
GameNews game = new GameNews(title, description,bmp,url);
// Add the new {#link Earthquake} to the list of earthquakes.
games.add(game);
}
} catch (JSONException e) {
Log.d(LOG_TAG, "" + e);
}
return games;
}
}
Thanks in advance.
I have would like to rewrite my method so that it returns a List of Movie class rather than a list of String class, here's the method I want to change:
private List<String> getMovieDataFromJson(String forecastJsonStr)
throws JSONException {
JSONObject movieJson = new JSONObject(forecastJsonStr);
JSONArray movieArray = movieJson.getJSONArray("results");
List<String> urls = new ArrayList<>();
for (int i = 0; i < movieArray.length(); i++) {
JSONObject movie = movieArray.getJSONObject(i);
urls.add("http://image.tmdb.org/t/p/w185" + movie.getString("poster_path"));
}
return urls;
}
I tried to rewrite it like this:
private List<Movie> getMovieDataFromJson(String forecastJsonStr)
throws JSONException {
JSONObject movieJson = new JSONObject(forecastJsonStr);
JSONArray movieArray = movieJson.getJSONArray("results");
List<Movie> movies = new ArrayList<>();
for (int i = 0; i < movieArray.length(); i++) {
JSONObject movie = movieArray.getJSONObject(i);
Movie movie1 = new Movie(movie.getString("original_title"), movie.getDouble("vote_average"), movie.getString("release_date"), movie.getString("overview"), movie.getString("poster_path"));
movies.add(movie1);
}
return movies;
}
But the problem is I'm getting error on line 139, it's saying required is String but found Movie instead. Here is line 139:
return getMovieDataFromJson(movieJsonStr);
Here is my code:
package com.projmobileapp.pmdbadd.pmdb;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
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;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MainActivityFragment extends Fragment {
//ArrayAdapter<String> mMovieAdapter;
//String[] movieId,movieTitle,movieOverview,movieReleaseDate,movieVoteAverage;
String[] moviePosterPath = new String[0];
public MainActivityFragment() {
}
MovieAdapter mMovieAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
mMovieAdapter = new MovieAdapter(getActivity());
GridView listView = (GridView) rootView.findViewById(R.id.gridview_movie);
listView.setAdapter(mMovieAdapter);
updateMovie();
return rootView;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
inflater.inflate(R.menu.mainactivityfragment, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_refresh) {
updateMovie();
return true;
}
return super.onOptionsItemSelected(item);
}
private void updateMovie() {
FetchMovieTask movieTask = new FetchMovieTask();
movieTask.execute();
}
class FetchMovieTask extends AsyncTask<Void, Void, List<String>> {
private final String LOG_TAG = FetchMovieTask.class.getSimpleName();
#Override
protected List<String> doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String movieJsonStr = null;
try {
URL url = new URL("http://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=INSERTAPIKEY");
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) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
movieJsonStr = buffer.toString();
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
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 getMovieDataFromJson(movieJsonStr);
} catch (JSONException j) {
Log.e(LOG_TAG, "JSON Error", j);
}
return null;
}
private List<String> getMovieDataFromJson(String forecastJsonStr)
throws JSONException {
JSONObject movieJson = new JSONObject(forecastJsonStr);
JSONArray movieArray = movieJson.getJSONArray("results");
List<String> urls = new ArrayList<>();
for (int i = 0; i < movieArray.length(); i++) {
JSONObject movie = movieArray.getJSONObject(i);
urls.add("http://image.tmdb.org/t/p/w185" + movie.getString("poster_path"));
}
return urls;
}
#Override
protected void onPostExecute(List<String> strings) {
mMovieAdapter.replace(strings);
}
}
class MovieAdapter extends BaseAdapter {
private final String LOG_TAG = MovieAdapter.class.getSimpleName();
private final Context context;
private final List<String> urls = new ArrayList<String>();
public MovieAdapter(Context context) {
this.context = context;
Collections.addAll(urls, moviePosterPath);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = new ImageView(context);
}
ImageView imageView = (ImageView) convertView;
String url = getItem(position);
Log.e(LOG_TAG, " URL " + url);
Picasso.with(context).load(url).into(imageView);
return convertView;
}
#Override
public int getCount() {
return urls.size();
}
#Override
public String getItem(int position) {
return urls.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public void replace(List<String> urls) {
this.urls.clear();
this.urls.addAll(urls);
notifyDataSetChanged();
}
}
}
The problem here is that your AsyncTask defines the result type for doInBackground() as List<String>. You need to change the line:
class FetchMovieTask extends AsyncTask<Void, Void, List<String>>
to
class FetchMovieTask extends AsyncTask<Void, Void, List<Movie>>
and change doInBackground() to return List<Movie>
Im trying to add the name of the resturaunt and the category onto a card view via custom adapter. How ever when ever i run the program i keep getting a java null pointer exception. Im a little bit startled by this, i have been looking through the web but have found no luck. Thanks in advance!
//Main:
package com.example.rifatrashid.compass;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Rifat Rashid on 2/23/2015.
*/
public class chooseactivity extends ActionBarActivity{
private ListView listView1;
ArrayList<Places> venuesList;
final String GOOGLE_KEY = "AIzaSyD72cNSZ6PoMFwvDe-ihUDNcTrAnuMynuE";
TextView t1;
final String latitude = "40.7463956";
final String longitude = "-73.9852992";
PlacesAdapter adapter1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chooselocation);
new googleplaces().execute();
/*Places place_data[] = new Places[]{
new Places("Lunch", "Mandarin Cuisine"),
new Places("Brunch", "Fredmeyer"),
new Places("Supplies", "Target")
};
*/
/*
PlacesAdapter adapter = new PlacesAdapter(this, R.layout.listview_item_row, place_data);
listView1 = (ListView) findViewById(R.id.listView);
listView1.setAdapter(adapter);
*/
}
class googleplaces extends AsyncTask<View, Void, String> { //Line54
String temp;
#Override
protected String doInBackground(View... urls) {
temp = makeCall("https://maps.googleapis.com/maps/api/place/search/json?location=" + latitude + "," + longitude + "&radius=100&sensor=true&key=" + GOOGLE_KEY);
return "";
}
#Override
protected void onPreExecute() {}
#Override
protected void onPostExecute(String result) {
if (temp == null) {
//Error coce exception
} else {
venuesList = (ArrayList<Places>) parseGoogleParse(temp);
List<String> listTitle = new ArrayList<>();
//List<Places> gPlace = new ArrayList<>();
Places[] place_data = new Places[100];
for (int i = 0; i < venuesList.size(); i++) {
//listTitle.add(i, venuesList.get(i).getName() + "\nOpen Now: " + venuesList.get(i).getOpenNow() + "\n(" + venuesList.get(i).getCategory() + ")");
new Places(venuesList.get(i).getCategory().toString(), venuesList.get(i).getName().toString()); //Line77
//gPlace.add(new Places(venuesList.get(i).getCategory(), "y"));
}
adapter1 = new PlacesAdapter(chooseactivity.this, R.layout.listview_item_row, place_data);
listView1 = (ListView) findViewById(R.id.listView);
listView1.setAdapter(adapter1);
}
}
}
public static String makeCall(String url) {
// string buffers the url
StringBuffer buffer_string = new StringBuffer(url);
String replyString = "";
// instanciate an HttpClient
HttpClient httpclient = new DefaultHttpClient();
// instanciate an HttpGet
HttpGet httpget = new HttpGet(buffer_string.toString());
try {
// get the responce of the httpclient execution of the url
HttpResponse response = httpclient.execute(httpget);
InputStream is = response.getEntity().getContent();
// buffer input stream the result
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(20);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
// the result as a string is ready for parsing
replyString = new String(baf.toByteArray());
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(replyString);
// trim the whitespaces
return replyString.trim();
}
private static ArrayList<Places> parseGoogleParse(final String response) {
ArrayList<Places> temp = new ArrayList<>();
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.has("results")) {
JSONArray jsonArray = jsonObject.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
Places poi = new Places();
if (jsonArray.getJSONObject(i).has("name")) {
poi.setName(jsonArray.getJSONObject(i).optString("name"));
poi.setRating(jsonArray.getJSONObject(i).optString("rating", " "));
if (jsonArray.getJSONObject(i).has("opening_hours")) {
if (jsonArray.getJSONObject(i).getJSONObject("opening_hours").has("open_now")) {
if (jsonArray.getJSONObject(i).getJSONObject("opening_hours").getString("open_now").equals("true")) {
poi.setOpenNow("YES");
} else {
poi.setOpenNow("NO");
}
}
} else {
poi.setOpenNow("Not Known");
}
if (jsonArray.getJSONObject(i).has("types")) {
JSONArray typesArray = jsonArray.getJSONObject(i).getJSONArray("types");
for (int j = 0; j < typesArray.length(); j++) {
poi.setCategory(typesArray.getString(j) + ", " + poi.getCategory());
}
}
}
temp.add(poi);
}
}
} catch (Exception e) {
e.printStackTrace();
return new ArrayList<Places>();
}
return temp;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
}
Heres my Places Class:
package com.example.rifatrashid.compass;
/**
* Created by Rifat Rashid on 2/23/2015.
*/
public class Places {
public String category;
public String name;
public String rating;
public String open;
public Places(){
super();
}
public Places(String category, String name){
super();
this.category = "";
this.name = "";
this.rating = "";
this.open = "";
}
public String getCategory(){
return category;
}
public String getOpen(){
return open;
}
public String getName(){
return name;
}
public void setName(String name) {
this.name = name;
}
public void setRating(String rating) {
this.rating = rating;
}
public void setOpenNow(String openNow) {
this.open = openNow;
}
public void setCategory(String s) {
}
public String getOpenNow() {
return open;
}
}
My custom adapter class:
package com.example.rifatrashid.compass;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
/**
* Created by Rifat Rashid on 2/23/2015.
*/
public class PlacesAdapter extends ArrayAdapter<Places> {
Context context;
int layoutResourceId;
Places[] data;
//List<Places> data;
public PlacesAdapter(Context context, int layoutResourceId, Places[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
public View getView(int position, View convertView, ViewGroup parent){
View row = convertView;
PlacesHolder holder = null;
if(row == null){
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new PlacesHolder();
holder.titleTxt = (TextView) row.findViewById(R.id.placeTitle);
holder.sub = (TextView) row.findViewById(R.id.placeCategory);
row.setTag(holder);
}else{
holder = (PlacesHolder) row.getTag();
}
Places place = data[position];
holder.titleTxt.setText(place.getName());
holder.sub.setText(place.getCategory());
return row;
}
static class PlacesHolder{
TextView titleTxt, sub;
}
}
Error:
02-26 17:05:30.530 9757-9757/com.example.rifatrashid.compass E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.rifatrashid.compass, PID: 9757
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
at com.example.rifatrashid.compass.chooseactivity$googleplaces.onPostExecute(chooseactivity.java:77)
at com.example.rifatrashid.compass.chooseactivity$googleplaces.onPostExecute(chooseactivity.java:54)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
As your error log says, you have a problem with a line in your onPostExecute method in your googleplaces class of your chooseactivity activity. (Line 77)
Specifically, one of the elements that you're trying to call toString() on is null.
new Places(venuesList.get(i).getCategory().toString(), venuesList.get(i).getName().toString()); //Line77
To fix the error (but not necessarily your process), wrap this in an if statement that checks to see if the element is null. Like this, for example:
if (venuesList.get(i) != null && venuesList.get(i).getCategory() != null && venuesList.get(i).getName() != null) {
new Places(venuesList.get(i).getCategory().toString(), venuesList.get(i).getName().toString()); //Line77
}
Now this won't actually fix your code, just prevent this error from occurring. What you should really do is in Android Studio, put a breakpoint on Line 77 so that when you debug, you can see exactly which element is null and track back why that might be the case and how you can intercept it in the future.
I have a button that gets month and year from spinners then calls an Async task, which read json data. That part works fine But if I try and change the month and year then click the button again it does nothing. I have to press back to reload the page to click the button again to get different results.
Here is my code. Can any of you smart folks please help me.
package com.app.simplictyPortal;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.apache.http.HttpResponse;
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 com.app.simplicityPortal.adapter.InvoiceAdapter;
import android.app.Fragment;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
public class InvoiceFragment extends Fragment {
public InvoiceFragment(){}
Button load;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_invoice, container, false);
ArrayList<String> years = new ArrayList<String>();
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
int currentMonth = Calendar.getInstance().get(Calendar.MONTH);
for (int i = 2013; i <= thisYear; i++)
{
years.add(Integer.toString(i));
}
//String tmonth = Integer.toString(currentMonth);
String tyear = Integer.toString(thisYear);
final Spinner year = (Spinner)rootView.findViewById(R.id.spinner1);
final Spinner month = (Spinner)rootView.findViewById(R.id.spinner2);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_item, years);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
year.setAdapter(adapter);
year.setSelection(adapter.getPosition(tyear));
ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(getActivity(),
R.array.month, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
month.setAdapter(adapter2);
month.setSelection(currentMonth);
load=(Button)rootView.findViewById(R.id.button1);
load.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String y = (String) year.getSelectedItem();
int im = month.getSelectedItemPosition();
String m = Integer.toString(im +1);
final GlobalClass globalVariable = (GlobalClass) getActivity().getApplicationContext();
final String Compid = globalVariable.getCompid();
new InvoiceAsyncTask().execute("http://dev-sql1:8080/api/invoice/getall/"+Compid+"?m="+m+"&y="+y);
}
});
return rootView;
}
public void invoice(JSONArray jArray) {
ListView lv = (ListView) getView().findViewById(R.id.listView1);
List<ListViewItem> items = new ArrayList<InvoiceFragment.ListViewItem>();
try {
for (int i = 0; i <jArray.length(); i++) {
final JSONObject json_data = jArray.getJSONObject(i);
items.add(new ListViewItem()
{{
Vendor= json_data.optString("CarrierName");
Bill = "$ " + json_data.optString("BillAmount");
Serviceacct = json_data.optString("ServiceAccountNumber");
Date = json_data.optString("ReceivedDate");
}});
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InvoiceAdapter adapter = new InvoiceAdapter(getActivity(), items);
lv.setAdapter(adapter);
// TODO Auto-generated method stub
}
public class ListViewItem
{
public String Vendor;
public String Bill;
public String Serviceacct;
public String Date;
} public static String GET(String url){
InputStream inputStream = null;
String result = "";
try {
// create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// make GET request to the given URL
HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
public class InvoiceAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return GET(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
try {
JSONArray jArray = new JSONArray(result);
invoice(jArray);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
How do you process results of your InvoiceAsyncTask? Do you implement a callback from your AsyncTask's onPostExecute() to the activity?
Maybe the sample below will help you.
First, implement AsyncTask class with callback interface:
public class ServerRequestAsyncTask extends AsyncTask<String, Void, ServerResponseDetails> {
public ServerRequestAsyncTask(Fragment fragment, ServerRequestDetails request) {
mFragment = fragment;
mRequest = request;
}
public interface OnServerRequestAsyncTaskCompletedListener {
void onServerRequestAsyncTaskCompleted(ServerResponseDetails response);
}
public void cancel() {
if (mHttpGet != null && !mHttpGet.isAborted()) mHttpGet.abort();
cancel(true);
}
And also add onPostExecute():
#Override
protected void onPostExecute(ServerResponseDetails response) {
if (mFragment != null) mFragment.onServerRequestAsyncTaskCompleted(response);
}
I call AsyncTask from Fragment, but you can use it with Activity instead.
Then, in your Activity you implement interface:
#Override
public void onServerRequestAsyncTaskCompleted(ServerResponseDetails response) {
// do what you need here, then 'finish' task by setting mServerRequest to null
mServerRequest = null;
}
And to execute AsyncTask:
protected ServerRequestAsyncTask mServerRequest = null;
public boolean isServerRequestRunning() {
return (mServerRequest != null);
}
public void cancelServerRequest() {
mServerRequest.cancel();
}
public void sendServerRequest(Fragment fragment, ServerRequestDetails request) {
if (Application.isNetworkAvailable()) {
if (!isServerRequestRunning()) {
mServerRequest = new ServerRequestAsyncTask(fragment, request);
mServerRequest.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
{params});
}
}
}
mServerRequest variable holds reference to currently executed task. You can call mServerRequest.cancel() if need to abort.
Thanks Everyone But I have figured it out. I needed to cancel the Async task in the post execute method.
#Override
protected void onPostExecute(String result) {
try {
JSONArray jArray = new JSONArray(result);
invoice(jArray);
cancel(true);
isCancelled();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
My application cannot read data from a server, but I can't find the error in my code or its error log. In fact, after checking my API, the link works fine. INTERNET and WRITE_EXTERNAL_STORAGE permission are already set in the manifest.
My code:
package com.berthojoris.bacaberita;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.berthojoris.bacaberita.adapter.BeritaAdapter;
import com.berthojoris.bacaberita.bean.BeritaBean;
import com.berthojoris.bacaberita.lib.Constants;
import com.berthojoris.bacaberita.lib.ImageLoader;
import com.berthojoris.bacaberita.lib.JSONParser;
import com.berthojoris.bacaberita.lib.Utils;
import com.berthojoris.bacaberita.sqlite.UtilBerita;
public class Berita extends ListActivity {
ProgressDialog dialog;
private static String urlBerita = "http://newapi.bacaberita.com/berita";
public ImageLoader imageLoader;
private JSONParser jParser;
Toast msg;
TextView notfound;
JSONArray contacts = null;
ArrayList<BeritaBean> AmbilDataBean = new ArrayList<BeritaBean>();
BeritaAdapter adapter;
UtilBerita UtilBerita;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dialog = new ProgressDialog(this);
UtilBerita = new UtilBerita(this);
imageLoader = new ImageLoader(this.getApplicationContext());
notfound = (TextView) findViewById(R.id.notfound);
notfound.setVisibility(View.GONE);
getListView().setVisibility(View.VISIBLE);
AmbilDataBean = new ArrayList<BeritaBean>();
adapter = new BeritaAdapter(this, AmbilDataBean);
setListAdapter(adapter);
Utils.setPolicyThread();
// Creating JSON Parser Instance
jParser = new JSONParser();
Log.e("Berita Activity", "TOTAL SIZE DATABASE : "
+ UtilBerita.ReadBerita().size());
if (UtilBerita.ReadBerita().size() < 1) {
Log.e("Berita Activity", "DATABASE KOSONG. JALANKAN ASYNC");
new async().execute();
} else {
AmbilDataBean = UtilBerita.ReadBerita();
adapter.setItem(AmbilDataBean);
Log.e("Berita Activity", "DATABASE DIAMBIL");
}
setTimerRefresh();
}// Tutup onCreate
private class async extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
AmbilDataBean = new ArrayList<BeritaBean>();
dialog.setMessage("Please wait...");
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
#Override
protected String doInBackground(Void... params) {
String jsonContent = jParser.getJSONDataFromUrl(urlBerita);
Log.e("Berita Activity", "PROSES BACKGROUND DIJALANKAN");
return jsonContent;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result.length() > 0) {
dialog.dismiss();
// parsing disini
JSONObject json = null;
try {
json = new JSONObject(result);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(Constants.TAG_ITEM);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(Constants.TAG_MenuID);
String judul = c.getString(Constants.TAG_Title);
//String img = c.getString(Constants.TAG_Link);
String desk = c.getString(Constants.TAG_Post);
String date = c.getString(Constants.TAG_Created);
BeritaBean mb = new BeritaBean();
mb.setID(id);
mb.setTitle(judul);
//mb.setLink("http://" + img);
mb.setPost(desk);
mb.setCreated(date);
AmbilDataBean.add(mb);
}
adapter.setItem(AmbilDataBean);
Log.e("Berita Activity",
"PROSES SELESAI. DATA AKAN DITAMPILKAN");
} catch (Exception e) {
dialog.dismiss();
Toast.makeText(getBaseContext(),
"Connection Error. Please try again...",
Toast.LENGTH_SHORT).show();
}
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
}
});
} catch (Exception e) {
dialog.dismiss();
Toast.makeText(getBaseContext(),
"Connection Error. Please try again...",
Toast.LENGTH_SHORT).show();
}
} // Tutup if (result.length() > 0)
else {
dialog.dismiss();
Toast.makeText(getBaseContext(),
"Data Not Found. Please try again...",
Toast.LENGTH_SHORT).show();
}
if (AmbilDataBean.size() < 1) {
notfound.setVisibility(View.VISIBLE);
getListView().setVisibility(View.GONE);
} else {
for (BeritaBean bean : AmbilDataBean) {
if (UtilBerita.getDetailWhereID(bean.getID()).getID() == null) {
Log.e("Berita Activity",
"Insert database : " + bean.getID());
UtilBerita.CreateData(bean);
} else {
Log.e("Berita Activity",
"Update database : " + bean.getID());
UtilBerita.UpdateBerita(bean);
}
}
notfound.setVisibility(View.GONE);
getListView().setVisibility(View.VISIBLE);
}
} // Tutup onPostExecute
} // Tutup private class async extends AsyncTask
// =========================================================================================================================
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.really_quit)
.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
finish();
}
}).setNegativeButton(R.string.no, null).show();
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}
// =========================================================================================================================
// Declare the timer
Timer timer = null;
final Handler handler = new Handler();
public void setTimerRefresh() {
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
Log.e("Main Activity", "RUNNING TASK...");
new async().execute();
}
});
}
}, 1000 * 60 * 1, 1000 * 25);
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (timer != null) {
timer.cancel();
timer = null;
}
if (UtilBerita != null)
UtilBerita.Close();
}
}
== UPDATE ==
My Constants class :
package com.berthojoris.bacaberita.lib;
public class Constants {
public static final String TAG_ITEM = "items";
public static final String TAG_MenuID = "Menu_ID";
public static final String TAG_IsDisplay = "IsDisplay";
public static final String TAG_CategoryName = "CategoryName";
public static final String TAG_CategoryID = "Category_ID";
public static final String TAG_ContentID = "Content_ID";
public static final String TAG_Title = "Title";
public static final String TAG_Post = "Post";
public static final String TAG_Link = "Link";
public static final String TAG_Meta = "Meta";
public static final String TAG_CreatedBy = "CreatedBy";
public static final String TAG_Created = "Created";
public static final String TAG_StartDisplay = "StartDisplay";
public static final String TAG_Counter = "counter";
}
You have to retrieve jsonArray from the jsonObject items. But in your code you have not used items anywhere. Try this way:
String jsonStr = new ConnectionService().connectionGet("http://newapi.bacaberita.com/berita","");
JSONObject jsonObject = new JSONObject(jsonStr);
System.out.println("..........JSON OBJECT.............");
System.out.println(jsonObject); // full json Object
JSONArray jsonArray = jsonObject.getJSONArray("items");
System.out.println("..........JSON ARRAY PARSING.............");
for(int i=0;i<jsonArray.length();i++)
{
String menu_id = jsonArray.getJSONObject(i).getString("Menu_ID");
String is_display = jsonArray.getJSONObject(i).getString("IsDisplay");
System.out.println("MENU_ID: "+menu_id);
System.out.println("IsDisplay: "+is_display);
}
The methods used in above example are as follows:
public static String connectionGet(String url, String parameter) throws MalformedURLException, ProtocolException, IOException {
URL url1 = new URL(url);
HttpURLConnection request1 = (HttpURLConnection) url1.openConnection();
request1.setRequestMethod("GET");
request1.connect();
String responseBody = convertStreamToString(request1.getInputStream());
return responseBody;
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} catch (IOException e) {
} finally {
try {
is.close();
} catch (IOException e) {
}
}
return sb.toString();
}