java.lang.RuntimeException: Unable to start activity ComponentInfo - android

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.

Related

Android Studio ListViewAdapter Error

please help me with this problem..
i change my previous question to this..
i cant post new question because im in danger of being blocked..
heres my problem..
im trying to get data from database but i got this error when i run the app..
09-29 13:41:07.032 26507-26507/? E/Error﹕ No value for result
09-29 13:41:07.032 26507-26507/? W/System.err﹕ org.json.JSONException: No value for result
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at org.json.JSONObject.get(JSONObject.java:354)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at org.json.JSONObject.getJSONArray(JSONObject.java:548)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at com.example.administrator.mosbeau.CategoryFragment.prepareListData(CategoryFragment.java:249)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at com.example.administrator.mosbeau.CategoryFragment$1GetDataJSON.onPostExecute(CategoryFragment.java:233)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at com.example.administrator.mosbeau.CategoryFragment$1GetDataJSON.onPostExecute(CategoryFragment.java:180)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at android.os.AsyncTask.finish(AsyncTask.java:631)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at android.os.AsyncTask.access$600(AsyncTask.java:177)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:99)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at android.os.Looper.loop(Looper.java:137)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5494)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:525)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:875)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:691)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
09-29 13:41:07.042 26507-26507/? I/MemoryCache﹕ MemoryCache will use up to 24.0MB
09-29 13:41:07.042 26507-26507/? D/AndroidRuntime﹕ Shutting down VM
09-29 13:41:07.042 26507-26507/? W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x418e38e0)
09-29 13:41:07.042 26507-26507/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.administrator.mosbeau.ListViewAdapter.getCount(ListViewAdapter.java:38)
at android.widget.ListView.setAdapter(ListView.java:463)
at com.example.administrator.mosbeau.CategoryFragment$1GetDataJSON.onPostExecute(CategoryFragment.java:236)
at com.example.administrator.mosbeau.CategoryFragment$1GetDataJSON.onPostExecute(CategoryFragment.java:180)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5494)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:875)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:691)
at dalvik.system.NativeStart.main(Native Method)
09-29 13:41:07.052 941-7799/? I/ActivityManager﹕ Notify an ApplicationCrash
here is the code..
CategoryFragment.java
package com.example.administrator.mosbeau;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ListView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by Administrator on 9/18/2015.
*/
public class CategoryFragment extends Fragment {
public static CategoryFragment newInstance(String id,String name) {
CategoryFragment fragment = new CategoryFragment();
Bundle bundle = new Bundle();
bundle.putString("id", id);
bundle.putString("name", name);
fragment.setArguments(bundle);
return fragment;
}
public CategoryFragment () {
}
EditText tpid, tpname;
String cid;
String cname;
String myJSON;
JSONObject jsonobject;
JSONArray jsonarray;
ListView productlistview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static final String result="result";
static String products_id = "products_id";
static String products_name = "products_name";
static String products_price = "products_price";
static String products_image = "products_image";
Boolean InternetAvailable = false;
Seocnd detectconnection;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.categorylayout, container, false);
getActivity().invalidateOptionsMenu();
tpid = (EditText) rootView.findViewById(R.id.tpid);
tpname = (EditText) rootView.findViewById(R.id.tpname);
if(getArguments() != null) {
String catid = getArguments().getString("id");
String catname = getArguments().getString("name");
tpid.setText(catid);
tpname.setText(catname);
cid = catid;
cname = catname;
}
productlistview = (ListView) rootView.findViewById(R.id.productlistview);
//new DownloadJSON().execute();
detectconnection = new Seocnd(getActivity());
InternetAvailable = detectconnection.InternetConnecting();
if (InternetAvailable) {
getProduct();
} else {
NointernetFragment fragment = new NointernetFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
return rootView;
}
public void getProduct(){
class GetDataJSON extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(getActivity());
// Set progressdialog title
mProgressDialog.setTitle(cname);
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://joehamirbalabadan.com/android/android/products.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
prepareListData();
adapter = new ListViewAdapter(getActivity(), arraylist);
// Set the adapter to the ListView
productlistview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
protected void prepareListData(){
try {
// Locate the array name in JSON
JSONObject jsonObj = new JSONObject(myJSON);
jsonarray = jsonObj.getJSONArray(result);
HashMap<String, String> map = new HashMap<String, String>();
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject p = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("products_id", p.getString("products_id"));
map.put("products_name", p.getString("products_name"));
map.put("products_price", p.getString("products_price"));
map.put("products_image", p.getString("products_image"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(2);
}
}
ListViewAdapter.java
package com.example.administrator.mosbeau;
/**
* Created by Administrator on 9/28/2015.
*/
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.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView products_id;
TextView products_name;
TextView products_price;
ImageView products_image;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.product_listview_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in product_listview_item.xml
products_id = (TextView) itemView.findViewById(R.id.products_id);
products_name = (TextView) itemView.findViewById(R.id.products_name);
products_price = (TextView) itemView.findViewById(R.id.products_price);
// Locate the ImageView in product_listview_item.xml
products_image = (ImageView) itemView.findViewById(R.id.products_image);
// Capture position and set results to the TextViews
products_id.setText(resultp.get(CategoryFragment.products_id));
products_name.setText(resultp.get(CategoryFragment.products_name));
products_price.setText(resultp.get(CategoryFragment.products_price));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(CategoryFragment.products_image), products_image);
// Capture ListView item click
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, SingleItemView.class);
// Pass all data rank
intent.putExtra("products_id", resultp.get(CategoryFragment.products_id));
// Pass all data country
intent.putExtra("products_name", resultp.get(CategoryFragment.products_name));
// Pass all data population
intent.putExtra("products_price",resultp.get(CategoryFragment.products_price));
// Pass all data flag
intent.putExtra("products_image", resultp.get(CategoryFragment.products_image));
// Start SingleItemView Class
context.startActivity(intent);
}
});
return itemView;
}
}
NEW ERROR
09-29 14:12:26.981 593-593/? W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x409bf1f8)
09-29 14:12:26.992 593-593/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.administrator.mosbeau.CategoryFragment.prepareListData(CategoryFragment.java:259)
at com.example.administrator.mosbeau.CategoryFragment$1GetDataJSON.onPostExecute(CategoryFragment.java:232)
at com.example.administrator.mosbeau.CategoryFragment$1GetDataJSON.onPostExecute(CategoryFragment.java:179)
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)
this is line 259
arraylist.add(map);
line 232
prepareListData();
UPDATED CODE
CategoryFragment.java
package com.example.administrator.mosbeau;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ListView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by Administrator on 9/18/2015.
*/
public class CategoryFragment extends Fragment {
public static CategoryFragment newInstance(String id,String name) {
CategoryFragment fragment = new CategoryFragment();
Bundle bundle = new Bundle();
bundle.putString("id", id);
bundle.putString("name", name);
fragment.setArguments(bundle);
return fragment;
}
public CategoryFragment () {
}
EditText tpid, tpname;
String cid;
String cname;
String myJSON;
JSONObject jsonobject;
JSONArray jsonarray;
ListView productlistview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
public static String products_id = "products_id";
public static String products_name = "products_name";
public static String products_price = "products_price";
public static String products_image = "products_image";
Boolean InternetAvailable = false;
Seocnd detectconnection;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.categorylayout, container, false);
getActivity().invalidateOptionsMenu();
tpid = (EditText) rootView.findViewById(R.id.tpid);
tpname = (EditText) rootView.findViewById(R.id.tpname);
if(getArguments() != null) {
String catid = getArguments().getString("id");
String catname = getArguments().getString("name");
tpid.setText(catid);
tpname.setText(catname);
cid = catid;
cname = catname;
}
productlistview = (ListView) rootView.findViewById(R.id.productlistview);
//new DownloadJSON().execute();
detectconnection = new Seocnd(getActivity());
InternetAvailable = detectconnection.InternetConnecting();
if (InternetAvailable) {
getProduct();
} else {
NointernetFragment fragment = new NointernetFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
return rootView;
}
public void getProduct(){
class DownloadJSON extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(getActivity());
// Set progressdialog title
mProgressDialog.setTitle(cname);
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://joehamirbalabadan.com/android/android/products.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
try {
// Locate the array name in JSON
JSONObject jsonObj = new JSONObject(myJSON);
jsonarray = jsonObj.getJSONArray("products");
arraylist = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject p = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("products_id", p.getString("products_id"));
map.put("products_name", p.getString("products_name"));
map.put("products_price", p.getString("products_price"));
map.put("products_image", p.getString("products_image"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
adapter = new ListViewAdapter(getActivity(), arraylist);
// Set the adapter to the ListView
productlistview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
DownloadJSON g = new DownloadJSON();
g.execute();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(2);
}
}
the image is not displaying when i use the .php file in this code..
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://joehamirbalabadan.com/android/android/products.php");
but when i use the .txt file it works..
i tried to copy the data of products.php and save it as .txt then when i change the link to this http://joehamirbalabadan.com/android/android/products.txt..
it works.. but i want to use the .php file because i use this to get the data from database..
products.php result
products.txt result
please help me..
Try to initialize arraylist first and also create HashMap item new instance inside for loop like :
protected void prepareListData(){
try {
arraylist = new ArrayList<HashMap<String, String>>();
// Locate the array name in JSON
JSONObject jsonObj = new JSONObject(myJSON);
jsonarray = jsonObj.getJSONArray(result);
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject p = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("products_id", p.getString("products_id"));
map.put("products_name", p.getString("products_name"));
map.put("products_price", p.getString("products_price"));
map.put("products_image", p.getString("products_image"));
// Set the JSON Objects into the array
arraylist.add(map);
}
catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
Initialize your result string with products like this one:
static final String result="products";
It will work
I think you need to decalre below variables
static final String result="result";
static String products_id = "products_id";
static String products_name = "products_name";
static String products_price = "products_price";
static String products_image = "products_image";
which you have to change like this
public static final String result="result";
public static String products_id = "products_id";
public static String products_name = "products_name";
public static String products_price = "products_price";
public static String products_image = "products_image";
I hope it work.

using fragment with asyncktask with notifydataset change

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;
}
}

Copy selected row data when click on row in listview and value send to new activity for display as textview

Hiiii I want when i should click the row data , it seems to copy the value of row and pass to another activity for display as textview. I am taking data by single row values from table using mysql. A "Hope of Help" will be appreciated from your side PLEASE !!
//MainActivity.java
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.widget.TextView;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
/*
* #author Firzan Ghulam
*/
public class MainActivity extends Activity{
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb = null;
ArrayList<String> al = new ArrayList<String>();
String targetmonth;
int responseCode;
int listItemCount=0;
ListView listview ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listview = (ListView) findViewById(R.id.listView1);
new LoadData().execute();
// listening to single list item on click
listview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
String product = ((TextView) view).getText().toString();
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), SingleListItem.class);
// sending data to new activity
i.putExtra("product", product);
startActivity(i);
}
});
}
private class LoadData extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
#Override
// can use UI thread here
protected void onPreExecute() {
this.progressDialog = ProgressDialog.show(MainActivity.this, ""," Can you just see your roof...");
}
#Override
protected void onPostExecute(final Void unused) {
try{
listview.setAdapter(new DataAdapter(MainActivity.this,al.toArray(new String[al.size()])));
this.progressDialog.dismiss();
}
catch(Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// HTTP post
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
HttpClient httpclient = new DefaultHttpClient();
try{
HttpPost httppost = new HttpPost("http://palaknehazz.com/app/ap.php");
StringEntity se = new StringEntity("envelope",HTTP.UTF_8);
httppost.setEntity(se);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 3000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
//buffered reader
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 80);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
System.out.println("Magu data aagaya"+result);
}
catch(Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
try{
jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
//targetamount=json_data.getString("targetamount");
targetmonth=json_data.getString("targetmonth");
//targetyear = json_data.getString("targetyear");
al.add(targetmonth);
//al1.add(targetyear);
//al2.add(targetamount);
//listItemCount=al2.size();
}
}
catch(JSONException e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
} catch (ParseException e) {
// Log.e("log_tag", "Error in http connection" + e.toString());
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
catch (Exception e) {
// Log.e("log_tag", "Error in http connection" + e.toString());
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
return null;
}
}
}
//Data Adapter
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class DataAdapter extends BaseAdapter {
Context mContext;
private LayoutInflater mInflater;
String targetmonth;
String[] month;
public DataAdapter(Context c, String[] month) {
this.month = month;
mContext = c;
mInflater = LayoutInflater.from(c);
}
public int getCount() {
return month.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.customgrid, parent, false);
holder = new ViewHolder();
holder.month = (TextView) convertView
.findViewById(R.id.targetmonth);
if (position == 0) {
convertView.setTag(holder);
}
} else {
holder = (ViewHolder) convertView.getTag();
}
try {
holder.month.setText(month[position]);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return convertView;
}
static class ViewHolder {
TextView month;
}
}
//SingleListItem
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class SingleListItem extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.meter);
TextView txtProduct = (TextView) findViewById(R.id.product_label);
Intent i = getIntent();
// getting attached intent data
String product = i.getStringExtra("product");
// displaying selected product name
txtProduct.setText(product);
}
}
//Logcat error
05-14 22:48:02.644: D/dalvikvm(461): GC_CONCURRENT freed 56K, 2% free 14428K/14663K, paused 8ms+6ms
05-14 22:48:03.051: D/gralloc_goldfish(461): Emulator without GPU emulation detected.
05-14 22:48:05.121: I/System.out(461): Magu data aagaya[{"id":"1","targetmonth":"Karan is a intelligegnt guy if you know what i mean haha frieds plays very important role i TV serial life i believe hahaha i mean who guess for being myself"},{"id":"2","targetmonth":"He's the unpredictable foolish man you are looking forward for seriously"},{"id":"3","targetmonth":"Same here you are looking"}]
05-14 22:48:08.294: D/AndroidRuntime(461): Shutting down VM
05-14 22:48:08.294: W/dalvikvm(461): threadid=1: thread exiting with uncaught exception (group=0x409961f8)
05-14 22:48:08.341: E/AndroidRuntime(461): FATAL EXCEPTION: main
05-14 22:48:08.341: E/AndroidRuntime(461): java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.widget.TextView
05-14 22:48:08.341: E/AndroidRuntime(461): at com.demo.php.listview.MainActivity$LoadData$1.onItemClick(MainActivity.java:94)
05-14 22:48:08.341: E/AndroidRuntime(461): at android.widget.AdapterView.performItemClick(AdapterView.java:292)
05-14 22:48:08.341: E/AndroidRuntime(461): at android.widget.AbsListView.performItemClick(AbsListView.java:1058)
05-14 22:48:08.341: E/AndroidRuntime(461): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2514)
05-14 22:48:08.341: E/AndroidRuntime(461): at android.widget.AbsListView$1.run(AbsListView.java:3168)
05-14 22:48:08.341: E/AndroidRuntime(461): at android.os.Handler.handleCallback(Handler.java:605)
05-14 22:48:08.341: E/AndroidRuntime(461): at android.os.Handler.dispatchMessage(Handler.java:92)
05-14 22:48:08.341: E/AndroidRuntime(461): at android.os.Looper.loop(Looper.java:137)
05-14 22:48:08.341: E/AndroidRuntime(461): at android.app.ActivityThread.main(ActivityThread.java:4340)
05-14 22:48:08.341: E/AndroidRuntime(461): at java.lang.reflect.Method.invokeNative(Native Method)
05-14 22:48:08.341: E/AndroidRuntime(461): at java.lang.reflect.Method.invoke(Method.java:511)
05-14 22:48:08.341: E/AndroidRuntime(461): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
05-14 22:48:08.341: E/AndroidRuntime(461): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
05-14 22:48:08.341: E/AndroidRuntime(461): at dalvik.system.NativeStart.main(Native Method)
in your main Activity change
// selected item
String product = ((TextView) view).getText().toString();
by
// selected item
String product = ((TextView) view.findViewById(R.id.targetmonth)).getText().toString();

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

Custom Listview force closing

I have created a custom list view which keeps force closing and I am having trouble figuring out why. I think I may have not named one of the view correctly since I was modeling this view off another. But I cant find my mistake yet.
Here is my force close error:
08-30 22:04:44.073 4011-4011/com.beerportfolio.beerportfoliopro E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.beerportfoliopro.BreweryLocationInfoAdapter.getView(BreweryLocationInfoAdapter.java:50)
at android.widget.AbsListView.obtainView(AbsListView.java:2410)
at android.widget.ListView.makeAndAddView(ListView.java:1963)
at android.widget.ListView.fillDown(ListView.java:815)
at android.widget.ListView.fillFromTop(ListView.java:876)
at android.widget.ListView.layoutChildren(ListView.java:1813)
at android.widget.AbsListView.onLayout(AbsListView.java:2238)
at android.view.View.layout(View.java:13900)
at android.view.ViewGroup.layout(ViewGroup.java:4391)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1649)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1507)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1420)
at android.view.View.layout(View.java:13900)
at android.view.ViewGroup.layout(ViewGroup.java:4391)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:13900)
at android.view.ViewGroup.layout(ViewGroup.java:4391)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1649)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1507)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1420)
at android.view.View.layout(View.java:13900)
at android.view.ViewGroup.layout(ViewGroup.java:4391)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:13900)
at android.view.ViewGroup.layout(ViewGroup.java:4391)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2183)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1984)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1221)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4710)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:746)
at android.view.Choreographer.doCallbacks(Choreographer.java:572)
at android.view.Choreographer.doFrame(Choreographer.java:538)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:731)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5536)
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:1074)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:841)
at dalvik.system.NativeStart.main(Native Method)
My BreweryLocationInfoAdapter code:
import java.util.List;
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.RatingBar;
import android.widget.TextView;
import com.beerportfolio.beerportfoliopro.R;
public class BreweryLocationInfoAdapter extends ArrayAdapter<BreweryLocationData>{
Context context;
int layoutResourceId;
List<BreweryLocationData> data = null;
public BreweryLocationInfoAdapter(Context context, int layoutResourceId, List<BreweryLocationData> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
breweryHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new breweryHolder();
holder.txtBrewery = (TextView)row.findViewById(R.id.beerNameList);
holder.txtDistance = (TextView)row.findViewById(R.id.beerBreweryNameList);
row.setTag(holder);
}
else
{
holder = (breweryHolder)row.getTag();
}
BreweryLocationData beer = data.get(position);
holder.txtBrewery.setText(beer.brewery);
holder.txtBrewery.setText(beer.distance);
return row;
}
static class breweryHolder
{
TextView txtBrewery;
TextView txtDistance;
}
}
GetNearbyBreweries code:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import com.beerportfolio.beerportfoliopro.R;
public class GetNearbyBreweries extends AsyncTask
<String, Void, String> {
Context c;
private ProgressDialog Dialog;
public GetNearbyBreweries (Context context)
{
c = context;
Dialog = new ProgressDialog(c);
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPreExecute() {
Dialog.setMessage("Locating Breweries");
Dialog.setTitle("Loading");
Dialog.setCancelable(false);
Dialog.show();
}
protected void onPostExecute(String result){
//decode json here
try{
JSONObject json = new JSONObject(result);
//acces listview
ListView lv = (ListView) ((Activity) c).findViewById(R.id.topTasteBeers);
//make array list for beer
final List<BreweryLocationData> tasteList = new ArrayList<BreweryLocationData>();
for(int i = 0; i < json.getJSONArray("data").length(); i++) {
String brewery = json.getJSONArray("data").getJSONObject(i).getJSONObject("brewery").getString("name");
String id = json.getJSONArray("data").getJSONObject(i).getJSONObject("brewery").getString("id");
String latitude = json.getJSONArray("data").getJSONObject(i).getString("latitude");
String longitude = json.getJSONArray("data").getJSONObject(i).getString("longitude");
String distance = json.getJSONArray("data").getJSONObject(i).getString("distance");
Toast.makeText(c, "Brewery: " + brewery, Toast.LENGTH_SHORT).show();
int count = i + 1;
//create object
BreweryLocationData tempLocation = new BreweryLocationData(brewery, id, longitude , latitude,distance);
//add to arraylist
tasteList.add(tempLocation);
//add items to listview
BreweryLocationInfoAdapter adapter1 = new BreweryLocationInfoAdapter(c ,R.layout.toptaste_layout, tasteList);
lv.setAdapter(adapter1);
//set up clicks
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
ShortBeerInfo o=(ShortBeerInfo)arg0.getItemAtPosition(arg2);
String tempID = o.id;
String tempBrewID = o.brewery;
Toast toast = Toast.makeText(c, tempID, Toast.LENGTH_SHORT);
toast.show();
//get beer details from id
Intent myIntent = new Intent(c, BeerPage2.class);
myIntent.putExtra("id", tempID);
myIntent.putExtra("breweryID", tempBrewID);
c.startActivity(myIntent);
}
});
}
}
catch(Exception e){
}
Dialog.dismiss();
}
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
}
I think for some reason row isn't getting created.
Can you double check by debugging that row != null by the time you arrive set row.setTag(holder).
I can only guess that 1. maybe the context you are using to get your inflater isn't correct, either way I prefer to use the following method
LayoutInflater.from(context).inflate(R.layout.cell, viewGroup, false);
Or, your resourceID is not right..
You have not written getCount method in your custom adapter:
public int getCount() {
return //Something here
}
Row 50 seems to be
holder.txtBrewery.setText(beer.brewery);
So either the TextView which should have id R.id.beerNameList has another id or beer.brewery is null.
You can solve these type of issues quickly if you use the debugger. Just put a breakpoint at the offending line, run the debugger and it will pause at the given line. You can then see exactly which object is null, allowing you to fix the problem in no time.
Don't hold the data in your custom adapter. Always use
BreweryLocationData beer = getItem(position);
to obtain the object that should be represented by the adapter. This way you can avoid issues with the data being modified outside of your adapter.

Categories

Resources