using fragment with asyncktask with notifydataset change - android

hi i want to download a json file from my server and add this json to list view i handle this on fragment with asyncktask method and list adapter
but i get this error
10-27 14:45:30.385: E/AndroidRuntime(2074): FATAL EXCEPTION: main
10-27 14:45:30.385: E/AndroidRuntime(2074): java.lang.NullPointerException
10-27 14:45:30.385: E/AndroidRuntime(2074): at com.mihanServer.Fragments.NewsFragment$JsonReader.onPostExecute(NewsFragment.java:89)
10-27 14:45:30.385: E/AndroidRuntime(2074): at com.mihanServer.Fragments.NewsFragment$JsonReader.onPostExecute(NewsFragment.java:1)
10-27 14:45:30.385: E/AndroidRuntime(2074): at android.os.AsyncTask.finish(AsyncTask.java:631)
10-27 14:45:30.385: E/AndroidRuntime(2074): at android.os.AsyncTask.access$600(AsyncTask.java:177)
10-27 14:45:30.385: E/AndroidRuntime(2074): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
10-27 14:45:30.385: E/AndroidRuntime(2074): at android.os.Handler.dispatchMessage(Handler.java:99)
10-27 14:45:30.385: E/AndroidRuntime(2074): at android.os.Looper.loop(Looper.java:137)
10-27 14:45:30.385: E/AndroidRuntime(2074): at android.app.ActivityThread.main(ActivityThread.java:5041)
10-27 14:45:30.385: E/AndroidRuntime(2074): at java.lang.reflect.Method.invokeNative(Native Method)
10-27 14:45:30.385: E/AndroidRuntime(2074): at java.lang.reflect.Method.invoke(Method.java:511)
10-27 14:45:30.385: E/AndroidRuntime(2074): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
10-27 14:45:30.385: E/AndroidRuntime(2074): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
10-27 14:45:30.385: E/AndroidRuntime(2074): at dalvik.system.NativeStart.main(Native Method)
this is my fragment code
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.mihanServer.sedasema.CustomListAdapter;
import com.mihanServer.sedasema.JSONParser;
import com.mihanServer.sedasema.MainActivity;
import com.mihanServer.sedasema.News;
import com.mihanServer.sedasema.R;
import android.app.ProgressDialog;
import android.database.DataSetObservable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.ListView;
public class NewsFragment extends Fragment {
private static final String url = "http://192.168.1.6/web/app_dev.php/news/list";
private List<News> newsList = new ArrayList<News>();
private ListView listView;
private CustomListAdapter adapter;
private JSONArray jArray;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.news , container, false);
listView = (ListView)rootView.findViewById(R.id.list);
try
{
adapter = new CustomListAdapter(getActivity(),newsList);
listView.setAdapter(adapter);
}
catch(Exception ex)
{
ex.printStackTrace();
}
new JsonReader().execute();
return rootView;
}
public class JsonReader extends AsyncTask<String, String, JSONObject>{
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array
jArray = json.getJSONArray("news");
for (int i = 0; i < jArray.length(); i++) {
try {
News news = new News();
JSONObject obj = jArray.getJSONObject(i);
news.setNewsTitle(obj.getString("title"));
news.setNewsThumbnailUrl(obj.getString("thumbnail"));
news.setNewsReleaseTime( obj.getString("created"));
news.setNewsBody(obj.getString("body"));
news.setNewsId(obj.getInt("id"));
// adding app to app array
newsList.add(news);
}
catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}
catch (JSONException ex){
ex.printStackTrace();
}
}
}
}
after line notify data set changed i get error.
this is my list adapter code
import com.mihanServer.sedasema.R;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.mihanServer.sedasema.MainActivity;
import com.mihanServer.sedasema.AppController;
import com.mihanServer.sedasema.News;
public class CustomListAdapter extends BaseAdapter {
private final Activity actitity;
private LayoutInflater inflater;
private List<News> newsItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
News news;
public CustomListAdapter(Activity activity,List<News> newsItems) {
this.newsItems = newsItems;
this.actitity =activity;
imageLoader = new AppController().getImageLoader();
}
#Override
public int getCount() {
return newsItems.size();
}
#Override
public Object getItem(int location) {
return newsItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final Context context = parent.getContext();
inflater = (LayoutInflater)context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
//inflater = (LayoutInflater) activity
// .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.news_list, null);
//comment for image reading
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView newsthumbnail = (NetworkImageView) convertView
.findViewById(R.id.news_image);
TextView newsTitle = (TextView) convertView.findViewById(R.id.news_title);
//TextView newsBody = (TextView) convertView.findViewById(R.id.news_body);
TextView newsReleaseTime = (TextView) convertView.findViewById(R.id.news_release_time);
// getting news data for the row
news = newsItems.get(position);
//comment for image reading
newsthumbnail.setImageUrl(news.getNewsThumbnailUrl(), imageLoader);
newsTitle.setText(news.getNewsTitle());
newsReleaseTime.setText( news.getNewsReleaseTime());
//newsBody.setText(news.getNewsBody());
convertView.setOnClickListener(new OnClickListener() {
//#Override
public void onClick(View arg0) {
news=newsItems.get(position);
Intent intent = new Intent(actitity.getApplicationContext(),NewsDetails.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("title",news.getNewsTitle());
intent.putExtra("body", news.getNewsBody());
intent.putExtra("newsimage", news.getNewsThumbnailUrl());
intent.putExtra("releasedtime", news.getNewsReleaseTime());
actitity.getApplicationContext().startActivity(intent);
}
});
return convertView;
}
}
and this is my json parser
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
static Socket socket = null;
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
try{
//try {
//URL urlS = new URL(url);
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
/*catch (UnknownHostException e) {
e.printStackTrace();
json = "UnknownHostException: " + e.toString();
}*/
//is = urlS.openStream();
//}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "");
}
is.close();
json = sb.toString();
//json = json.replace(""", "\"");
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
}/*catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
json = "IOException: " + e.toString();*/
// }
finally{
if(socket != null){
try {
socket.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return jObj;
}
}
i also use volley lib for download images like this
http://www.androidhive.info/2014/07/android-custom-listview-with-image-and-text-using-volley/

try with below changes in your adapter class:
public class CustomListAdapter extends BaseAdapter {
private final Activity actitity;
private LayoutInflater inflater;
private List<News> newsItems;
private AQuery aQuery;
//ImageLoader imageLoader = AppController.getInstance().getImageLoader();
News news;
public CustomListAdapter(Activity activity,List<News> newsItems) {
this.newsItems = newsItems;
this.actitity =activity;
aQuery=new AQuery(activity);
// imageLoader = new AppController().getImageLoader();
}
#Override
public int getCount() {
return newsItems.size();
}
#Override
public Object getItem(int location) {
return newsItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final Context context = parent.getContext();
inflater = (LayoutInflater)context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
//inflater = (LayoutInflater) activity
// .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.news_list, null);
//comment for image reading
/*if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();*/
NetworkImageView newsthumbnail = (NetworkImageView) convertView
.findViewById(R.id.news_image);
TextView newsTitle = (TextView) convertView.findViewById(R.id.news_title);
//TextView newsBody = (TextView) convertView.findViewById(R.id.news_body);
TextView newsReleaseTime = (TextView) convertView.findViewById(R.id.news_release_time);
// getting news data for the row
news = newsItems.get(position);
if(news.getNewsThumbnailUrl().length()>0){
aQuery.id(newsthumbnail).image(news.getNewsThumbnailUrl(),true,true);
}else{
newsthumbnail.setVisibility(View.GONE);
}
//comment for image reading
//newsthumbnail.setImageUrl(news.getNewsThumbnailUrl(), imageLoader);
newsTitle.setText(news.getNewsTitle());
newsReleaseTime.setText( news.getNewsReleaseTime());
//newsBody.setText(news.getNewsBody());
convertView.setOnClickListener(new OnClickListener() {
//#Override
public void onClick(View arg0) {
news=newsItems.get(position);
Intent intent = new Intent(actitity.getApplicationContext(),NewsDetails.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("title",news.getNewsTitle());
intent.putExtra("body", news.getNewsBody());
intent.putExtra("newsimage", news.getNewsThumbnailUrl());
intent.putExtra("releasedtime", news.getNewsReleaseTime());
actitity.getApplicationContext().startActivity(intent);
}
});
return convertView;
}
}

Related

Making an app that recieves Json data from tmdb.org

I am trying to make an app where I want my app, on launch, to display a grid of popular movie posters. The movie posters are downloaded from TheMovieDataBase API. I then use Picasso to load the images. For the GridView I am also using a custom adapter. I am not able to understand how to do it. Here is what I have done up till now
MovieFragment.java
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 MovieFragment extends Fragment {
//ArrayAdapter<String> mMovieAdapter;
String[]movieId,movieTitle,movieOverview,
movieReleaseDate,
moviePosterPath,movieVoteAverage;
public MovieFragment() {
}
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);
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.menu_fragment, 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=c20129fdf73b5df3ab44548ad7f73586");
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();
}
}
}
When I run this code it shows a NullPointerException and a RuntimeException
java.lang.RuntimeException: Unable to start activity ComponentInfo
{com.codesetters.verader/com.codesetters.verader.MainActivity}: java.lang.NullPointerException atandroid.app.ActivityThreadperformLaunchActivity(ActivityThread.java:2404)
Caused by: java.lang.NullPointerException atjava.util.Collections.addAll(Collections.java:2582)
How can I resolve them?
Please Help
You're getting this error because you've used moviePosterPath here :
Collections.addAll(urls, moviePosterPath);
but you've not initialized it anywhere. Initialize it with some value and it should solve the error.
The null pointer could be because the String array moviePosterPath is not initialized. and you are ussing it in Collections.addAll
This is how to initialize an array. Anyway I recommend you to use ArrayList
String[] moviePosterPath = new String[N];

Android - Null pointer on setAdapter function

I'm working on an app and I'm trying to show a listview filled with information from a MySQL database. I already have a different activity where I send and receive from the database using php, I'm doing something similar. I'm not sure if the error I'm having is something with the adapter class or from the Json Parsing part in the AsyncTask. These are the files:
package com.example.xxx.xxx;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
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.util.ArrayList;
public class ListActivity extends ActionBarActivity {
ListView list;
ArrayList<Places> placeslist;
PlacesAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_row);
placeslist = new ArrayList<Places>();
new JASONTask().execute("http://xxx.xxx.com/getlist.php");
adapter = new PlacesAdapter(getApplicationContext(), R.layout.single_row, placeslist);
list = (ListView)findViewById(R.id.listView);
list.setAdapter(adapter);
}
public class JASONTask extends AsyncTask<String,Void,Boolean>{
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(ListActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean 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 finalJson = buffer.toString();
JSONArray theJson = new JSONArray(finalJson);
for (int i=0; i<theJson.length(); i++){
Places place = new Places();
JSONObject jRealObject = theJson.getJSONObject(i);
place.setPlaces_id(jRealObject.getString("places_id"));
place.setName(jRealObject.getString("name"));
place.setLocation_address(jRealObject.getString("location_address"));
placeslist.add(place);
}
} 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 true;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if (result == false){
//message not parsed
}
}
}
}
The Places class is:
package com.example.xxx.xxx;
/**
* Created by manhols on 10/12/2015.
*/
public class Places {
private String places_id;
private String name;
private String location_address;
public Places(){
}
public String getPlaces_id() {
return places_id;
}
public void setPlaces_id(String places_id) {
this.places_id = places_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation_address() {
return location_address;
}
public void setLocation_address(String location_address) {
this.location_address = location_address;
}
}
And the PlacesAdapter class is:
package com.example.xxx.xxx;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by manhols on 10/12/2015.
*/
public class PlacesAdapter extends ArrayAdapter<Places>{
ArrayList<Places> placeslist;
int Resource;
Context context;
LayoutInflater vi;
public PlacesAdapter(Context context, int resource, ArrayList<Places> objects) {
super(context, resource, objects);
Resource = resource;
placeslist = objects;
vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
vi.inflate(Resource, null);
convertView = vi.inflate(Resource,null);
holder = new ViewHolder();
holder.textView = (TextView)convertView.findViewById(R.id.textView);
holder.textView2 = (TextView)convertView.findViewById(R.id.textView2);
holder.textView5 = (TextView)convertView.findViewById(R.id.textView5);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
holder.textView.setText(placeslist.get(position).getName());
holder.textView2.setText(placeslist.get(position).getPlaces_id());
holder.textView5.setText(placeslist.get(position).getLocation_address());
return convertView;
}
static class ViewHolder {
public TextView textView;
public TextView textView2;
public TextView textView5;
}
}
I will highly appreciate any help solving this issue.
I have spotted some errors in your adapter. Please inflate row as convertView = vi.inflate(Resource,parent,false); and also in parsing the data , return true only in try block. From your code i can see that even if you have an exception, you will be returning true which is wrong.
My problem was in the setContentView as #codeMagic mentioned before. I already solved this thanks to him

AsyncTask in Fragment not working and shows FATAL EXCEPTION: AsyncTask #1

The following code when run crashes my app. I am calling it in the MainActivity. When run it tells me:
FATAL EXCEPTION: AsyncTask #1 and directs me toward the ProgressDialog and Http Response Line
import android.app.Fragment;
import android.app.ProgressDialog;
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.EditText;
import android.widget.ListView;
import com.montel.senarivesselapp.model.ShowDataList;
import com.montel.senarivesselapp.model.Vessel;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpResponseException;
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 java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
public class ShowallFragment extends Fragment {
//variables for JSON query
private static final String name ="vessel_name";
private static final String etad="eta_date";
private static final String etat="eta_time";
private static final String etbd="etb_date";
private static final String etbt="etb_time";
private static final String shippingName="shipping_agent_name";
private static final String v1 = "vessels";
private static final String v2 = "Vessel";
private ArrayList<Vessel> vList = new ArrayList<>();
private ArrayAdapter arrayAdapter = null;
private ListView listView = null;
private EditText et = null;
private ShowDataList ssadapter = null;
private View rootView;
public ShowallFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_showall, container, false);
setContentView(R.layout.fragment_showall);
setRetainInstance(true);
return rootView;
}
private void setContentView(int fragment_showall) {
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
//For getting the JSON schedule from server
class Schedule extends AsyncTask<String, String, String> {
ProgressDialog loadDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
//Show the loading dialog
loadDialog = new ProgressDialog(ShowallFragment.this);
loadDialog.setMessage("Please wait....");
loadDialog.setCancelable(false);
loadDialog.show();
}
#Override
protected String doInBackground(String... uri) {
BufferedReader input = null;
String data = null;
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(new HttpGet("http://"));
StatusLine stline = response.getStatusLine();
if (stline.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
data = out.toString();
out.close();
} else {
response.getEntity().getContent().close();
throw new IOException(stline.getReasonPhrase());
}
} catch (HttpResponseException he) {
he.printStackTrace();
} catch (ClientProtocolException cpe) {
cpe.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
return data;
} catch (Exception e) {
System.out.println(e);
}
}
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Fill the vList array
Log.d("POST EXECUTE", result.toString());
loadDialog.dismiss();
if (result != null) {
try {
JSONObject jo = new JSONObject(result);
JSONArray vessels = jo.getJSONArray(v1);
Log.d("VESSEL LOG", vessels.toString());
vList = new ArrayList();
for (int i = 0; i < vessels.length(); i++) {
JSONObject vv = vessels.getJSONObject(i);
Log.d("VESSEL NAME", vv.getJSONObject(v2).getString(name));
vList.add(new Vessel(vv.getJSONObject(v2).getString(name),
vv.getJSONObject(v2).getString(etad),
vv.getJSONObject(v2).getString(etat),
vv.getJSONObject(v2).getString(etbd),
vv.getJSONObject(v2).getString(etbt),
vv.getJSONObject(v2).getString(shippingName)));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
listView = (ListView) rootView.findViewById(R.id.dataShow);
listView.setAdapter(arrayAdapter);
ssadapter = new ShowDataList(ShowallFragment.this , vList);
listView.setAdapter(ssadapter);
}
}
}
SecurityException: Permission denied (missing INTERNET permission
So you should request INTERNET permission in your projects AndroidManifest.xml file. Add on the rigth place:
<uses-permission android:name="android.permission.INTERNET" />
in your onPostExecute() change the position of Log.d("POST EXECUTE", result.toString()); to be inside catch so your code will look like this:
catch (Exception ee) {
ee.printStackTrace();
}
catch (JSONException e) {
Log.d("POST EXECUTE", e.toString());
} // catch (JSONException e)

java.lang.NullPointerException in getting data to ListView in Android

Hie Friends
I have one ListView which displays image data from JSON parser for that I use Custom Base Adapter.
But I got following exception.
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.ecard.ECard_main$AsycLove.onPostExecute(ECard_main.java:193)
at com.example.ecard.ECard_main$AsycLove.onPostExecute(ECard_main.java:1)
at android.os.AsyncTask.finish(AsyncTask.java:602)
at android.os.AsyncTask.access$600(AsyncTask.java:156)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
My Code Is:
package com.example.ecard;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import com.loopj.android.image.SmartImageView;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ECard_main extends Activity
{
String catagories;
String anim_id,album_id,anim_name,anim_thumb,anim_url;
TextView title;
SmartImageView image;
ListView hlv;
ArrayList<HashMap<String, String>> albumList;
#Override
protected void onCreate(Bundle savedInstanceState)
{
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.ecard_main);
Intent i=getIntent();
catagories=i.getExtras().getString("Catagories");
title=(TextView)findViewById(R.id.tv_main_title);
image=(SmartImageView)findViewById(R.id.IV_image);
title.setText(catagories);
//hlv = getListView();
hlv = (ListView) findViewById(android.R.id.list);
albumList = new ArrayList<HashMap<String, String>>();
new AsycLove().execute();
}
class AsycLove extends AsyncTask<String, String, String>
{
ProgressDialog progressDialog;
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = new ProgressDialog(ECard_main.this);
progressDialog.setTitle("Loading");
progressDialog.setMessage("Please wait");
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(true);
progressDialog.show();
}
#Override
protected String doInBackground(String... aurl)
{
try
{
HttpPost postMethod = new HttpPost("http://demo1.idevtechnolabs.com/smartecard/love.php");
BufferedReader bufferedReader = null;
HttpClient client = new DefaultHttpClient();
HttpResponse response = null;
response = client.execute(postMethod);
final int statusCode = response.getStatusLine().getStatusCode();
Log.v("Album ::","Response:::--->"+response.toString());
Log.v("Album ::","Status Code:::--->"+statusCode);
bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer stringBuffer = new StringBuffer("");
String line = "";
String LineSeparator = System.getProperty("line.separator");
while ((line = bufferedReader.readLine()) != null)
{
stringBuffer.append(line + LineSeparator);
}
bufferedReader.close();
//-------------CONVERT DATA TO JSON---------------------------------
try
{
String myjsonstring = stringBuffer.toString();
JSONArray jsonArray = new JSONArray(myjsonstring);
JSONObject jsonObj = null;
albumList.clear();
jsonObj = jsonArray.getJSONObject(0);
for(int i=0; i<jsonArray.length();i++)
{
jsonObj = jsonArray.getJSONObject(i);
anim_id = jsonObj.getString("animation_id");
album_id = jsonObj.getString("album_id");
anim_name = jsonObj.getString("animation_name");
anim_thumb= jsonObj.getString("animation_thumb");
anim_url = jsonObj.getString("animation_url");
anim_url=anim_url.replaceAll("\"","");
Log.v("Anim URL","Anim URL::"+anim_url);
Log.v("Anim Name","Anim Name::"+anim_name);
HashMap<String, String> tmp_album = new HashMap<String, String>();
tmp_album.put("anim_id", anim_id);
tmp_album.put("anim_thumb", anim_thumb);
albumList.add(tmp_album);
}
}
catch (Exception e)
{
Log.v("Home ::","Call JSON Exception in get Album in List--->"+e.toString());
e.printStackTrace();
}
}
catch (IOException e)
{
Log.v("Exception: Get get Album in List","Name-"+e.toString());
e.printStackTrace();
}
return "0";
}
#Override
protected void onPostExecute(String code)
{
Toast.makeText(getApplicationContext(), "Image URL Call Successfully", Toast.LENGTH_LONG).show();
Log.v("Album","Album List::"+albumList);
ECard_main_Custom_Adapter adapter =new ECard_main_Custom_Adapter(getApplicationContext(),albumList);
hlv.setAdapter(adapter);
progressDialog.dismiss();
progressDialog = null;
}
}
}
And My Adapter Is:
import java.util.ArrayList;
import java.util.HashMap;
import com.loopj.android.image.SmartImageView;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
public class ECard_main_Custom_Adapter extends BaseAdapter
{
private Context context;
ArrayList<HashMap<String, String>> listAlbum;
ViewHolder vholder;
Drawable image;
public ECard_main_Custom_Adapter(Context context, ArrayList<HashMap<String, String>> albumList)
{
this.context = context;
this.listAlbum=albumList;
}
#Override
public int getCount()
{
Log.v("1","1");
return listAlbum.size();
}
#Override
public Object getItem(int position)
{
Log.v("1","2");
return position;
}
#Override
public long getItemId(int position)
{
Log.v("1","3");
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
Log.v("1","1");
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View vi=convertView;
vi = inflater.inflate(R.layout.ecard_main_adapter, null);
vholder = new ViewHolder();
vholder.img_album=(SmartImageView)vi.findViewById(R.id.IV_image);
vi.setTag(vholder);
try
{
String anim_id=listAlbum.get(position).get("anim_id");
String url=listAlbum.get(position).get("anim_thumb");
Log.v("Anim ID and Anim URL","Id:"+anim_id+" URL:"+url);
vholder.img_album.setImageUrl(url);
}
catch (Exception e)
{
// TODO: handle exception
Log.v("Error Ecard","Error is:::"+e);
}
return vi;
}
static class ViewHolder
{
SmartImageView img_album;
}
}
Please tell me where I am wrong.
Any help is appreciated.
Thanks In advance.
First correct this
hlv = (ListView) findViewById(android.R.id.list);
to
hlv = (ListView) findViewById(R.id.list);
It might cause an error. and make sure your ecard_main.xml layout contains ListView with id list

java.lang.RuntimeException: Unable to start activity ComponentInfo

I'm trying to code a tweeter feed but i have an error for the compilation.
I don't forget to add my activity into the manifest.
Here is the activity code :
package fr.enstb.tp2;
import java.net.URL;
import java.util.ArrayList;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
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.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class TweetsActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<Tweet> tweets = getTweets("android", 1);
ListView listView = (ListView) findViewById(R.id.ListViewId);
listView.setAdapter(new UserItemAdapter(this, R.layout.tweets_layout, tweets));
}
public class UserItemAdapter extends ArrayAdapter<Tweet> {
private ArrayList<Tweet> tweets;
public UserItemAdapter(Context context, int textViewResourceId, ArrayList<Tweet> tweets) {
super(context, textViewResourceId, tweets);
this.tweets = tweets;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.tweets_layout, null);
}
Tweet tweet = tweets.get(position);
if (tweet != null) {
TextView username = (TextView) v.findViewById(R.id.username);
TextView message = (TextView) v.findViewById(R.id.message);
ImageView image = (ImageView) v.findViewById(R.id.avatar);
if (username != null) {
username.setText(tweet.username);
}
if(message != null) {
message.setText(tweet.message);
}
if(image != null) {
image.setImageBitmap(getBitmap(tweet.image_url));
}
}
return v;
}
}
public Bitmap getBitmap(String bitmapUrl) {
try {
URL url = new URL(bitmapUrl);
return BitmapFactory.decodeStream(url.openConnection() .getInputStream());
}
catch(Exception ex) {return null;}
}
public ArrayList<Tweet> getTweets(String searchTerm, int page) {
String searchUrl = "http://search.twitter.com/search.json?q=#"
+ searchTerm + "&rpp=100&page=" + page;
ArrayList<Tweet> tweets = new ArrayList<Tweet>();
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(searchUrl);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = null;
try{
responseBody = client.execute(get, responseHandler);
}catch(Exception ex) {
ex.printStackTrace();
}
JSONObject jsonObject = null;
JSONParser parser=new JSONParser();
try {
Object obj = parser.parse(responseBody);
jsonObject=(JSONObject)obj;
}catch(Exception ex){
Log.v("TEST","Exception: " + ex.getMessage());
}
JSONArray arr = null;
try {
Object j = jsonObject.get("results");
arr = (JSONArray)j;
}catch(Exception ex){
Log.v("TEST","Exception: " + ex.getMessage());
}
for(Object t : arr) {
Tweet tweet = new Tweet(
((JSONObject)t).get("from_user").toString(),
((JSONObject)t).get("text").toString(),
((JSONObject)t).get("profile_image_url").toString()
);
tweets.add(tweet);
}
return tweets;
}
public class Tweet {
public String username;
public String message;
public String image_url;
public Tweet(String username, String message, String url) {
this.username = username;
this.message = message;
this.image_url = url;
}
}
}
And here is the log traces :
: E/AndroidRuntime(884): FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{fr.enstb.tp2/fr.enstb.tp2.TweetsActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955)
at android.app.ActivityThread.startActivityNow(ActivityThread.java:1796)
at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:135)
at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:347)
at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:682)
at android.widget.TabHost.setCurrentTab(TabHost.java:346)
at android.widget.TabHost$2.onTabSelectionChanged(TabHost.java:150)
at android.widget.TabWidget$TabClickListener.onClick(TabWidget.java:540)
at android.view.View.performClick(View.java:3460)
at android.view.View$PerformClick.run(View.java:13955)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4340)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at fr.enstb.tp2.TweetsActivity.getTweets(TweetsActivity.java:126)
at fr.enstb.tp2.TweetsActivity.onCreate(TweetsActivity.java:36)
at android.app.Activity.performCreate(Activity.java:4465)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919)
... 18 more
Thankk for your help !
According to the stacktrace, your arr variable in getTweets() must be null since you get a NullPointerException on this line: for(Object t : arr)
Step through the code with the debugger and see what you get back from the service call.

Categories

Resources