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
Related
I using listview to display the response from API, which is a JSON object. Below listview, a button will be there. On clicking that button I need to get all the data from listview in JSON format.
Activity Class
package com.aryvart.myaromasupply;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ListView;
import com.aryvart.myaromasupply.Adapter.CartListAdapterKV;
import com.aryvart.myaromasupply.Bean.CommonBean;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
/**
* Created by android01 on 28/8/17.
*/
public class CartPageKV extends Activity implements MyInterface {
String json = null;
List<CommonBean> movieList = new ArrayList<>();
RecyclerView recyclerView;
CartListAdapterKV mAdapter;
Context context;
CoordinatorLayout coordinatorLayout;
Button btn_submit;
HashMap<String, JSONObject> hsFilterGmap;
String value;
JSONArray jsonArray;
ListView llView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cart_page_kv);
context = this;
recyclerView = (RecyclerView) findViewById(R.id.my_recyclerView);
btn_submit = (Button) findViewById(R.id.btn_submit);
coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinator_layout);
llView = (ListView) findViewById(R.id.ll_view);
loadJSONFromAsset();
//Response API
try {
JSONObject obj = new JSONObject(json);
Log.e("NN", "json-->" + obj.toString());
JSONArray respArray = obj.getJSONArray("results");
Log.e("NN", "respArray-->" + respArray.toString());
for (int i = 0; i < respArray.length(); i++) {
JSONObject jsonObj = respArray.getJSONObject(i);
CommonBean drawerBean = new CommonBean();
drawerBean.setStr_cart_id(jsonObj.getString("id"));
drawerBean.setStr_cart_title(jsonObj.getString("name"));
drawerBean.setStr_quan(jsonObj.getString("quantity"));
drawerBean.setStr_tot_quant(jsonObj.getString("total_quantity"));
movieList.add(drawerBean);
}
// Getting adapter by passing xml data ArrayList
mAdapter = new CartListAdapterKV(movieList, context, (MyInterface) context);
llView.setAdapter(mAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
//Button Click Event
btn_submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e("NN:fc", String.valueOf(hsFilterGmap));
Iterator myVeryOwnIterator = hsFilterGmap.keySet().iterator();
JSONArray jsonArray = new JSONArray();
while (myVeryOwnIterator.hasNext()) {
String key = (String) myVeryOwnIterator.next();
JSONObject value1 = hsFilterGmap.get(key);
Log.e("NN:value", value1.toString());
jsonArray.put(value1);
}
Log.e("NN:fcAr", jsonArray.toString().replaceAll("\\\\", ""));
System.out.println("the JSON ARRAY is" + jsonArray.toString());
}
});
}
public String loadJSONFromAsset() {
try {
InputStream is = getAssets().open("data.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
// Interface to get Checked value from listview(Hashmap for not allowing duplicates)
#Override
public HashMap<String, JSONObject> getUnCheckedVal(HashMap<String, JSONObject> strVal, String str_removed_id) {
hsFilterGmap = strVal;
Log.e("NN:fc", String.valueOf(hsFilterGmap));
return hsFilterGmap;
}
}
Adapter Class
package com.aryvart.myaromasupply.Adapter;
import android.content.Context;
import android.support.v7.widget.CardView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import com.aryvart.myaromasupply.Bean.CommonBean;
import com.aryvart.myaromasupply.MyInterface;
import com.aryvart.myaromasupply.R;
import com.like.LikeButton;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.List;
/**
* Created by android01 on 28/8/17.
*/
public class CartListAdapterKV extends BaseAdapter {
private List<CommonBean> commonBeanList;
Context c;
MyInterface my_interface;
private static LayoutInflater inflater = null;
HashMap<String, JSONObject> hsMap = new HashMap<String, JSONObject>();
// constructor
public CartListAdapterKV(List<CommonBean> movieList, Context context, MyInterface inter) {
this.commonBeanList = movieList;
Log.e("NN", "size-->" + this.commonBeanList);
this.c = context;
this.my_interface = inter;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return commonBeanList.size();
}
public Object getItem(int position) {
return commonBeanList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (convertView == null)
view = inflater.inflate(R.layout.cart_items_kv, parent, false);
TextView txt_cartTitle;
final CheckBox cb_box;
txt_cartTitle = (TextView) view.findViewById(R.id.textView2);
cb_box = (CheckBox) view.findViewById(R.id.checkBoxKV);
final CommonBean recyclerBean = commonBeanList.get(position);
cb_box.setChecked(true);
txt_cartTitle.setText(recyclerBean.getStr_cart_title());
//check if checkbox is checked. if yes the add value to hashmap(by default all checkboxes will be checked in listview
if (cb_box.isChecked()) {
Toast.makeText(c, "--" + recyclerBean.getStr_cart_title(), Toast.LENGTH_SHORT).show();
//JSONArray req = new JSONArray();
JSONObject jsoBj = new JSONObject();
try {
jsoBj.put("id", recyclerBean.getStr_cart_id());
jsoBj.put("value", recyclerBean.getStr_cart_title());
jsoBj.put("checked", "true");
} catch (JSONException e) {
e.printStackTrace();
}
hsMap.put(recyclerBean.getStr_cart_id(), jsoBj);
my_interface.getUnCheckedVal(hsMap, recyclerBean.getStr_cart_id());
Log.e("NN", "AdpaMap--" + hsMap.toString());
} else {
JSONObject jsoBj = new JSONObject();
try {
jsoBj.put("id", recyclerBean.getStr_cart_id());
jsoBj.put("value", recyclerBean.getStr_cart_title());
jsoBj.put("checked", "false");
} catch (JSONException e) {
e.printStackTrace();
}
//adding the json object in hashmap to remove duplicates
hsMap.put(recyclerBean.getStr_cart_id(), jsoBj);
my_interface.getUnCheckedVal(hsMap, recyclerBean.getStr_cart_id());
Toast.makeText(c, "-*-" + recyclerBean.getStr_cart_title(), Toast.LENGTH_SHORT).show();
}
cb_box.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
final CommonBean recyclerBean = commonBeanList.get(position);
if (cb_box.isChecked()) {
Toast.makeText(c, "--" + recyclerBean.getStr_cart_title(), Toast.LENGTH_SHORT).show();
JSONObject jsoBj = new JSONObject();
try {
jsoBj.put("id", recyclerBean.getStr_cart_id());
jsoBj.put("value", recyclerBean.getStr_cart_title());
jsoBj.put("checked", "true");
} catch (JSONException e) {
e.printStackTrace();
}
hsMap.put(recyclerBean.getStr_cart_id(), jsoBj);
my_interface.getUnCheckedVal(hsMap, recyclerBean.getStr_cart_id());
Log.e("NN", "AdpaMap--" + hsMap.toString());
} else {
JSONObject jsoBj = new JSONObject();
try {
jsoBj.put("id", recyclerBean.getStr_cart_id());
jsoBj.put("value", recyclerBean.getStr_cart_title());
jsoBj.put("checked", "false");
} catch (JSONException e) {
e.printStackTrace();
}
hsMap.put(recyclerBean.getStr_cart_id(), jsoBj);
my_interface.getUnCheckedVal(hsMap, recyclerBean.getStr_cart_id());
Toast.makeText(c, "-*-" + recyclerBean.getStr_cart_title(), Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
}
On initial clicking of a button, I'm getting the data which is in the foreground (visible to the user), once I scroll remaining data's are getting.
Can anyone help how can I get entire values in listview in on button click?
Open this cart_items_kv xml and place the button.
Go to the adapter
and make the event there.You can get the data of an item by position in adapter.
another solution
add a click after finding view
public ViewHolder(View itemLayoutView) {
// here `enter code here`
itemLayoutView.setOnClickListener(this);
}
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
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.
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;
}
}
I'm just new to android and java and i m trying to build a sample android application.
I picked up application view from androhive looks like google+ app
and made my function following to many tutorials online
but i'm unable to integrate them.
here are my codes
Here is my fragment sample which is used in switching activity using sidebar
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MHEFragment extends Fragment {
public MHEFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
return rootView;
}
}
Heres my function os listview
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
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.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
private String jsonResult;
private String url = "http://192.168.129.1/1.php";
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView1);
accessWebService();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrwaer();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void ListDrwaer() {
List<Map<String, String>> storyList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("story");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("story_name");
String number = jsonChildNode.getString("story_id").toString();
String outPut = number + "-" + name;
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View name, int position,
long number) {
Intent intnt = new Intent(getApplicationContext(), Tester.class);
String deta = adapter.getItemAtPosition(position).toString();
String myStr = deta.replaceAll( "[^\\d]", "" );
intnt.putExtra(EXTRA_MESSAGE,myStr);
startActivity(intnt);
}
});
storyList.add(createStory("stories", outPut));
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
SimpleAdapter simpleAdapter = new SimpleAdapter(this, storyList,
android.R.layout.simple_list_item_1,
new String[] { "stories" }, new int[] { android.R.id.text1 });
listView.setAdapter(simpleAdapter);
}
private HashMap<String, String> createStory(String name, String number) {
HashMap<String, String> storyNameNo = new HashMap<String, String>();
storyNameNo.put(name, number);
return storyNameNo;
}
}
How can i integrate my listview in above fragment?
If you want ListView in fragment then you'd be better off using your Fragment which would subclass ListFragment.
And the onCreateView() from ListFragment will return a ListView that you can populate.
http://developer.android.com/reference/android/app/ListFragment.html
http://www.vogella.com/tutorials/AndroidListView/article.html#listfragments
For Fragments, if you want a separate ListView and more in one fragment, it'l help if you go through:
http://www.easyinfogeek.com/2013/07/full-example-of-using-fragment-in.html
..for what is more to the layout and calling onCreateView()
Also, (not a part of the question, but from & for your code) if it helps, i'd suggest
Use a for each loop where you can instead of for(;;)
(in your case at: for each json child node in json main node)
http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html
How does the Java 'for each' loop work?