How to solve empty costume list view issue? - android

I have written a code to get all the videos related to a specific user in YouTube as follows:
import java.util.ArrayList;
import java.util.Collection;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.DefaultClientConnection;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import com.example.tstnetconnwithjson.tables.custome;
import com.example.tstnetconnwithjson.tables.videos;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
Button search; ;
TextView name ;
ListView listview ;
ArrayList<videos > videolist;
ArrayAdapter< videos > adapter ;
AlertDialog.Builder alert ;
ProgressDialog progressdialog ;
EditText name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
videolist = new ArrayList<videos>();
adapter = new ArrayAdapter<videos>(this, android.R.layout.simple_list_item_1 , android.R.id.text1,videolist);
name=(EditText) findViewById(R.id.editText1);
alert = new Builder(this);
alert.setTitle("Warnning" ) ;
alert.setMessage("You want to connect to the internet ..? " );
alert.setNegativeButton("No ", null);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
String username=name.getText().toString();
new connection().execute("https://gdata.youtube.com/feeds/api/videos?author="+username+"&v=2&alt=jsonc");
}
});
progressdialog = new ProgressDialog(this);
progressdialog.setMessage("Wait Loading .... ");
progressdialog.setCancelable(false);
search = (Button) findViewById(R.id.button1);
name = (TextView) findViewById(R.id.textView1);
listview = (ListView) findViewById(R.id.listView1);
listview.setAdapter(adapter);
search.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
alert.show();
}
});
}
class connection extends AsyncTask<String, Integer, String>{
#Override
protected void onPreExecute() {
progressdialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
String s = GetUrlBody(arg0[0]);
return s;
}
#Override
protected void onPostExecute(String result) {
try{
JSONObject jo =(JSONObject) new JSONTokener(result).nextValue();
JSONObject feed = jo.optJSONObject("data");
JSONArray entry = feed.optJSONArray("items");
for(int i = 0 ; i<entry.length() ; i++){
String title = entry.getJSONObject(i).getString("title");
String thumbURL = entry.getJSONObject(i).getJSONObject("thumbnail").getString("sqDefault");
Log.d("after get image", "ok")
String url;
try {
url = entry.getJSONObject(i).getJSONObject("player").getString("mobile");
} catch (JSONException ignore) {
url = entry.getJSONObject(i).getJSONObject("player").getString("default");
}
String description = entry.getJSONObject(i).getString("description");
Log.d("after get description", "ok");
videos videoobject=new videos();
videoobject.setDecscrption(description);
videoobject.setImageurl(thumbURL);
videoobject.setVediourl(url);
videoobject.setVideoname(title);
videolist.add(videoobject);
}
listview.setAdapter(new custome(MainActivity.this,videolist));
Log.d("AFTER set custome ", "before notify changes");
adapter.notifyDataSetChanged();
}catch(Exception exception) {
Log.d("exception ", "nock nock nock....");
Log.e("json ", exception.getMessage());
}
progressdialog.dismiss();
super.onPostExecute(result);
}
String GetUrlBody (String Url ){
HttpClient client = new DefaultHttpClient();
HttpGet gethttp = new HttpGet(Url);
try{
HttpResponse response = client.execute(gethttp);
if(response.getStatusLine().getStatusCode() == 200){
String save =
EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
return save;
}else {
return "Not Found";
}
}catch(Exception exception){}
return null;
}
}
}
Where the custome class is extends from base adapter in order to have list view with image view set to video image and text view set to video title.
In log cat messages the result are existed but my list view returns empty.
Can any one tell me why?
here is the code for costume list view:
public class custome extends BaseAdapter {
ArrayList<videos> data=new ArrayList<videos>();
android.content.Context context1;
android.widget.TextView name;
ImageView picture;
public custome(Context context,ArrayList<videos>arrayList) {
// TODO Auto-generated constructor stub
context=context;
arrayList=data;
}
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return data.get(arg0);
}
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
public View getView(int arg0, View arg1, ViewGroup arg2) {
View view=arg1;
if(view==null)
{
LayoutInflater layoutInflater=(LayoutInflater) _c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view=layoutInflater.inflate(R.layout.listvideo,null);
}
name=(TextView) view.findViewById(R.id.textView1);
picture=(ImageView) view.findViewById(R.id.imageView1);
videos video = data.get(arg0);
name.setText(video.getVideoname());
URL url = null;
try {
url = new URL(video.getImageurl());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
picture.setImageBitmap(bitmap);
return view;
}
}

The problem is in your assigning code of custome constructor:
Use this constructor:
public custome(Context context,ArrayList<videos> arrayList) {
context=context;
//arrayList=data;<<< WRONG
data=arrayList;//<<<<<<< Correct way of assigning
}

You are overriding your adapter here:
listview.setAdapter(new custome(MainActivity.this,videolist));
Remove this line

Related

how to work on BUY NOW button in android?

I am developing an Android eCommerce application in which there are two different buttons. The first one is an ADD TO CART button and the other one is a BUY NOW button.
When I click on the ADD TO CART button, it successfully places the item in the cart and after I click on the cart button, the app proceeds to the Cart Activity. I did the same for BUY NOW but the issue is how do I update my cart and move to Cart Activity on a single click?
ProductDescription.java:
package com.www.prashant;
import android.app.ProgressDialog;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.daimajia.slider.library.SliderLayout;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
public class ProductDescription extends Fragment {
View V;
int position;
ImageView product_image;
TextView product_desc;
public TextView price;
public TextView specialPrice;
TextView product_name;
ImageLoader image;
SliderLayout product_images;
Button sharbtn;
public TextView txt_qty;
public Button btn_plus;
public Button btn_buy;
ProgressDialog pdialog;
public int sum=0;
public int remove=0;
String cartMessage;
String cartMessage1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((MainActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
((MainActivity)getActivity()).actionBarDrawerToggle.setDrawerIndicatorEnabled(false);
Constants.lastDetails = true;
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.product_details, container, false);
//Set Navigation mode as Statndard
((MainActivity)getActivity()).getSupportActionBar().setNavigationMode(((MainActivity) getActivity()).getSupportActionBar().NAVIGATION_MODE_STANDARD);
V=v;
//get Product Position
position = Constants.product_position;
//Initialize ids
product_image=(ImageView) V.findViewById(R.id.product_image);
product_desc=(TextView) V.findViewById(R.id.textProductDescription);
price=(TextView) V.findViewById(R.id.text1);
specialPrice = (TextView) V.findViewById(R.id.textSpecialPrice);
product_name=(TextView) V.findViewById(R.id.textProductName);
//sharbtn=(Button)V.findViewById(R.id.sharbtn);
image=new ImageLoader(getActivity());
image.DisplayImage(Constants.Product_image.get(position), product_image);
product_name.setText(Constants.Product_name.get(position));
product_desc.setText(Constants.Product_desc.get(position));
// product_adesc.setText(Constants.Product_adesc.get(position));
if(Constants.Product_specialPrice.get(position) < Constants.Product_price.get(position)
&& Constants.Product_specialPrice.get(position)!=0){
price.setText(String.format("%.2f",Constants.Product_price.get(position)));
price.setPaintFlags(price.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
specialPrice.setText(String.format("%.2f",Constants.Product_specialPrice.get(position)));
}
else {
price.setText(String.format("%.2f",Constants.Product_price.get(position)));
specialPrice.setText(null);
}
btn_plus = (Button) V.findViewById(R.id.btn_plus);
btn_buy = (Button) V.findViewById(R.id.btn_buy);
// btn_minus = (ImageButton) V.findViewById(R.id.btn_minus);
txt_qty = (TextView) V.findViewById(R.id.txt_qty);
txt_qty.setText(String.valueOf(Constants.Product_qty.get(position)));
**/* Button Click Listener for Add Qty*/**
btn_plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Constants.Product_pos=position;
remove=0;
sum = Integer.parseInt(txt_qty.getText().toString())+1;
Constants.Product_qty.set(position, sum);
cartMessage1="Adding product to cart...";
cartMessage="Product was added successfully";
new updateCart().execute();
}
});
**/* Button Click Listener for Buy Qty*/**
btn_buy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Constants.Product_pos=position;
remove=0;
sum = Integer.parseInt(txt_qty.getText().toString())+1;
Constants.Product_qty.set(position, sum);
cartMessage1="Adding product to cart...";
cartMessage="Product was added successfully";
new updateCart().execute();
}
});
product_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ImageFragment imageFrag=new ImageFragment();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.main_content,imageFrag,null).addToBackStack(null).commit();
getActivity().setTitle("Images");
}
});
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
//((MainActivity)getActivity()).resetActionBar(true, DrawerLayout.LOCK_MODE_LOCKED_OPEN);
super.onActivityCreated(savedInstanceState);
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
((MainActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
((MainActivity)getActivity()).actionBarDrawerToggle.setDrawerIndicatorEnabled(true);
MainActivity.getInstance().CallFragment(Constants.position);
}
return true;
}
//Add product to cart task
public class updateCart extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
if (pdialog==null){
pdialog=new ProgressDialog(getActivity());
pdialog.setMessage(cartMessage1);
pdialog.setCanceledOnTouchOutside(false);
pdialog.setCancelable(false);
pdialog.show();
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
parseJSONDataAddProductToCart();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
if (pdialog.isShowing()){
pdialog.dismiss();
pdialog=null;
}
Toast.makeText(getActivity(), cartMessage, Toast.LENGTH_LONG).show();
//Update Notification Count in action bar icon
//Constants.cart_count += 1;
//txt_qty.setText(String.valueOf(sum));
MainActivity.getInstance().updateHotCount(Constants.ProductCart_Id.size());
txt_qty.setText(String.valueOf(Constants.Product_qty.get(position)));
// if internet connection and data available show data on list
// otherwise, show alert text
}
}
//Remove product from cart
public class removeCartProduct extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
if (pdialog==null){
pdialog=new ProgressDialog(getActivity());
pdialog.setMessage(cartMessage1);
pdialog.setCanceledOnTouchOutside(false);
pdialog.setCancelable(false);
pdialog.show();
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
parseJSONDataAddProductToCart();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
if (pdialog.isShowing()){
pdialog.dismiss();
pdialog=null;
}
Toast.makeText(getActivity(), cartMessage,Toast.LENGTH_LONG).show();
//Update Notification Count in action bar icon
//Constants.cart_count -= 1;
//txt_qty.setText(String.valueOf(sum));
MainActivity.getInstance().updateHotCount(Constants.ProductCart_Id.size());
txt_qty.setText(String.valueOf(Constants.Product_qty.get(position)));
// if internet connection and data available show data on list
// otherwise, show alert text
}
}
public void parseJSONDataAddProductToCart(){
try {
SoapObject item = new SoapObject(Constants.NAMESPACE, "shoppingCartProductEntity");
SoapObject request;
int qty;
if(remove==0){
request = new SoapObject(Constants.NAMESPACE, "shoppingCartProductAdd");
qty=1;
}else{
qty= Constants.Product_qty.get(Constants.Product_pos);
if(qty==0){
request = new SoapObject(Constants.NAMESPACE, "shoppingCartProductRemove");
}else{
request = new SoapObject(Constants.NAMESPACE, "shoppingCartProductUpdate");
}
}
// add paramaters and values
request.addProperty("sessionId", Constants.sessionId);
PropertyInfo pinfo = new PropertyInfo();
pinfo.setName("product_id");
pinfo.setValue(Constants.Product_ID.get(Constants.Product_pos));
pinfo.setType(String.class);
item.addProperty(pinfo);
pinfo = new PropertyInfo();
pinfo.setName("qty");
pinfo.setValue(qty);
pinfo.setType(Double.class);
item.addProperty(pinfo);
SoapObject EntityArray = new SoapObject(Constants.NAMESPACE, "shoppingCartProductEntityArray");
EntityArray.addProperty("products", item);
request.addProperty("quoteId", Constants.cartId);
request.addProperty("products",EntityArray);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
//Web method call
HttpTransportSE androidHttpTransport = new HttpTransportSE(Constants.URL);
androidHttpTransport.debug = true;
androidHttpTransport.call("", envelope);
//get the response
Object result = envelope.getResponse();
Constants.CartaddStatus=result.toString();
if(Constants.CartaddStatus == "true"){
if (Constants.ProductCart_Id.isEmpty()){
Constants.cartArrayPos=0;
}
if (!Constants.ProductCart_Id.contains(Constants.Product_ID.get(Constants.Product_pos))) {
Constants.ProductCart_Id.add(Constants.cartArrayPos,Constants.Product_ID.get(Constants.Product_pos));
Constants.ProductCart_Img.add(Constants.cartArrayPos,Constants.Product_image.get(Constants.Product_pos));
Constants.ProductCart_Price.add(Constants.cartArrayPos, Constants.Product_price.get(Constants.Product_pos));
Constants.cartArrayPos+=1;
}
if (qty==0){
Constants.ProductCart_Id.remove(Constants.Product_pos);
Constants.ProductCart_Img.remove(Constants.Product_pos);
Constants.ProductCart_Price.remove(Constants.Product_pos);
Constants.cartArrayPos-=1;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
}
}
ActivityCart:
package com.www.prashant;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
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.JSONArray;
import org.json.JSONObject;
import org.json.simple.parser.JSONParser;
/**
* Created by Prashant on 10/16/2016.
*/
public class ActivityCart extends Fragment {
int run;
ProgressDialog pdialog;
View v;
GridView list2;
CartImageLoadAdapter adapter;
public static ActivityCart sActivityCart;
public Double TotalPrice= 0.00;
TextView btn_place_order;
TextView btn_place;
Button btn_place_ord;
static String TotalProductCartPrice;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.cart, container, false);
sActivityCart = this;
((MainActivity)getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(true);
((MainActivity)getActivity()).getSupportActionBar().setNavigationMode(((MainActivity) getActivity()).getSupportActionBar().NAVIGATION_MODE_STANDARD);
list2=(GridView)v.findViewById(R.id.cartlist);
//list2.setBackgroundColor(Color.BLACK);
//list2.setVerticalSpacing(1);
// list2.setHorizontalSpacing(1);
clearData();
btn_place_order = (TextView) v.findViewById(R.id.btn_place_order);
// btn_place = (TextView) v.findViewById(R.id.btn_place);
btn_place_ord = (Button) v.findViewById(R.id.btn_place_ord);
btn_place_ord.setOnClickListener(listener);
return v;
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Constants.lastDetails = false;
((AppCompatActivity) getActivity()).getSupportActionBar().setSubtitle(null);
((MainActivity)getActivity()).actionBarDrawerToggle.setDrawerIndicatorEnabled(true);
Constants.cartEntry=1;
new getDataTask().execute();
}
void clearData(){
Constants.Product_ID.clear();
Constants.Product_name.clear();
Constants.Product_price.clear();
Constants.Product_image.clear();
Constants.Product_qty.clear();
Constants.Product_specialPrice.clear();
Constants.Product_desc.clear();
//Constants.Product_adesc.clear();
}
#Override
public void onDestroy()
{
// Remove adapter refference from list
if (run==1) {
list2.setAdapter(null);
//Refresh cache directory downloaded images
adapter.imageLoader.clearCache();
adapter.notifyDataSetChanged();
}
super.onDestroy();
}
//Click Listner for place order button
public View.OnClickListener listener=new View.OnClickListener(){
#Override
public void onClick(View arg0) {
if(run == 1) {
// Call Login Function
if(Constants.Customer_FirstName.equals(""))
{
CartLogin CartLogin=new CartLogin();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.main_content,CartLogin,null).addToBackStack(null).commit();
getActivity().setTitle("Login");
}
else {
// Call Shipping Information Function
ActivityCustomerAddress CustomerAddress=new ActivityCustomerAddress();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.main_content,CustomerAddress,null).addToBackStack(null).commit();
getActivity().setTitle("Shipping");
}
}
else
Toast.makeText(getActivity(),"Cart is Empty",Toast.LENGTH_LONG).show();
}
};
// Image urls used in LazyImageLoadAdapter.java file
public class getDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
if (pdialog==null){
pdialog=new ProgressDialog(getActivity());
pdialog.setMessage("Loading...");
pdialog.setCanceledOnTouchOutside(getRetainInstance());
pdialog.setCancelable(false);
pdialog.show();
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
if (!Constants.ProductCart_Id.isEmpty()){
parseJSONData();
run=1;
}else{
run=0;
}
//Get Product Prices
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
// Create custom adapter for listview
if (run==1) {
String[] images = new String[Constants.Product_image.size()];
images = Constants.Product_image.toArray(images);
adapter = new CartImageLoadAdapter(getActivity(), images);
//Set adapter to listview
list2.setAdapter(adapter);
if (pdialog.isShowing()) {
pdialog.dismiss();
pdialog = null;
}
}else{
if (pdialog.isShowing()) {
pdialog.dismiss();
pdialog = null;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Cart is Empty").setMessage("Start Shopping now !!").create().show();
run=0;
}
// if internet connection and data available show data on list
// otherwise, show alert text
// btn_place_order.setText(String.format("Total: %.2f Place Order", TotalPrice));
btn_place_order.setText(String.format("%.2f ", TotalPrice));
TotalProductCartPrice= btn_place_order.getText().toString();
}
}
// method to parse json data from server
public void parseJSONData(){
HttpClient Client = new DefaultHttpClient();
// Create URL string
String URL = "http://prashant.com/customApi/cartDetails.php?cartId="+Constants.cartId;
//Log.i("httpget", URL);
JSONParser parser =new JSONParser();
try
{
String SetServerString = "";
// Create Request to server and get response
HttpGet httpget = new HttpGet(URL);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
SetServerString = Client.execute(httpget, responseHandler);
Constants.Login=SetServerString;
JSONArray array=new JSONArray(SetServerString);
for (int i = 0; i < array.length(); i++) {
JSONObject obj=array.getJSONObject(i);
Constants.Product_ID.add(Long.parseLong(obj.getString("productId")));
Constants.Product_name.add(obj.getString("name"));
Double price= Double.valueOf(obj.getString("price"));
int Qty= Integer.parseInt(obj.getString("qty"));
Constants.Product_price.add(price*Qty);
Constants.Product_image.add(obj.getString("imageurl"));
Constants.Product_qty.add(Integer.valueOf(obj.getString("qty")));
Constants.Product_specialPrice.add((Double.valueOf(obj.getString("spprice")))*Qty);
// Total Sum of Cart Item price
TotalPrice += Double.valueOf(Double.valueOf(obj.getString("spprice"))*Qty);
}
// Show response on activity
}
catch(Exception ex)
{
}
}
public static ActivityCart getInstance() {
return sActivityCart;
}
public void SyncCart(){
// Call Shipping Information Function
ActivityCart SyncCart=new ActivityCart();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.main_content,SyncCart,null).addToBackStack(null).commit();
getActivity().setTitle("Cart");
}
}

add click Listner in each item of row in Listview

i want add clickable link in android listview item, i have 5 item in each row of listview and i want only two item make clickable and open sholud in webview using putextras() intents i am using custom adapter pls any one hlep me.
suppose "link 1" is: "view Proofing"(proofinglink) (in textview) and "link 2" is : "Get More Detail"(sitelink) i want when i click link 1 then it should open in webview behind his own given url . and when i click on link 2: it should also open in webview in his own given url. using putextras() intents
here is my code.
package tipster;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import newsletter.Latest_list;
import newsletter.Webview_news;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
import com.example.newapp.R;
public class Tipster extends Activity {
ListView lv;
ArrayList<Tipster_list>listitem;
String title;
String serviceUrl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tipster);
if (isNetworkAvailable()) {
// Execution here
// Toast.makeText(this, "Network is Available!",
Toast.LENGTH_LONG).show();
execute();
title="Free Tip - Betfans";
lv=(ListView) findViewById(R.id.listView_tipsterID);
listitem=new ArrayList<Tipster_list>();
}
else {
Toast.makeText(this, "Network is unavailable!",
Toast.LENGTH_LONG).show();
}
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private void execute() {
serviceUrl ="http://mobile.betfan.com/api/?
Action=top&type=default&key=MEu07MgiuWgXwJOo7Oe1aHL0yM8VvP";
//Toast.makeText(LatestNews.this, serviceUrl, Toast.LENGTH_LONG).show();
class LoginAsync extends AsyncTask<String, Void, String>{
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(Tipster.this, "Please
while wait", "Loading...");
}
#Override
protected String doInBackground(String... params) {
JSONObject jsonObject = new JSONObject();
String dataString = jsonObject.toString();
InputStream is = null;
List<NameValuePair> nameValuePairs = new
ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("data", dataString));
String result = null;
try{
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet();
URI apiurl = new URI(serviceUrl);
httpRequest.setURI(apiurl);
HttpResponse response = httpClient.execute(httpRequest);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new
InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
protected void onPostExecute(String result){
String s = result.trim();
loadingDialog.dismiss();
JSONObject respObject;
try {
respObject = new JSONObject(s);
String active = respObject.getString("status_message");
if(active.equalsIgnoreCase("success")){
JSONArray array =
respObject.getJSONArray("response");
for (int i =0; i<array.length();i++){
JSONObject jsonObject = array.getJSONObject(i);
String icon= jsonObject.getString("image");
String name = jsonObject.getString("name");
String total = jsonObject.getString("total");
String proofinglink =
jsonObject.getString("proofinglink");
String sitelink = jsonObject.getString("sitelink");
listitem.add(new
Tipster_list(icon,name,"+"+total,proofinglink,sitelink));
}
lv.setAdapter(new Tipster_adapter(Tipster.this,
listitem));
}else {
Toast.makeText(Tipster.this, "services received
Fail", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
String getName=listitem.get(arg2).getName();
String
getproofing=listitem.get(arg2).getProofinglink();
String getsite=listitem.get(arg2).getSitelink();
Intent intent = new Intent(getApplicationContext(),
Tipster_webview.class);
intent.putExtra("gettproofing_URl",getproofing);
intent.putExtra("getsiteURL",getsite);
startActivity(intent);
}
});
}
}
LoginAsync la = new LoginAsync();
la.execute();
}
i want "proofinglink" and "sitelink" should be clickable and open in webview
here is custom adapter
public class Tipster_adapter extends BaseAdapter {
Context context;
ArrayList<Tipster_list>tipslist;
public Tipster_adapter(Context context,
ArrayList<Tipster_list> tipslist) {
super();
this.context = context;
this.tipslist = tipslist;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return tipslist.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null){
LayoutInflater inflater=(LayoutInflater)
context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView=inflater.inflate(R.layout.activity_tipster_adapter
,null);
ImageView icon=
(ImageView)convertView.findViewById(R.id.icon_tipsterIconID);
TextView name=(TextView)
convertView.findViewById(R.id.txt_name_tipsterID);
TextView total=(TextView)
convertView.findViewById(R.id.txt_total_tipsterID);
TextView proofingLink=(TextView)
convertView.findViewById(R.id.txt_proofinglink_tipsterID);
TextView siteLink=(TextView)
convertView.findViewById(R.id.txt_sitelink_tipsterID);
Tipster_list services=tipslist.get(position);
Picasso.with(context).load(services.getImage()).into(icon);
Log.d("Url",services.getImage());
name.setText(services.getName());
total.setText(services.getTotal());
proofingLink.setText(services.getProofinglink());
siteLink.setText(services.getSitelink());
}
return convertView;
}
}
your code is ok you need to add a listener in your adapter for the view on which you want to fire an intent for example
inside your adapter getview method paste this code like this
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Tipster_list services=tipslist.get(position);
if(services!=null){
LayoutInflater inflater=(LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView=inflater.inflate(R.layout.activity_custom_adapter,null);
ImageView icon=(ImageView)convertView.findViewById(R.id.icon_tipsterIconID);
TextView name=(TextView) convertView.findViewById(R.id.txt_name_tipsterID);
TextView total=(TextView) convertView.findViewById(R.id.txt_total_tipsterID);
TextView proofingLink=(TextView) convertView.findViewById(R.id.txt_proofinglink_tipsterID);
TextView siteLink=(TextView) convertView.findViewById(R.id.txt_sitelink_tipsterID);
Picasso.with(context).load(services.getImage()).into(icon);
Log.d("Url",services.getImage());
name.setText(services.getName());
total.setText(services.getTotal());
proofingLink.setText(services.getProofinglink());
siteLink.setText(services.getSitelink());
convertView.setTag(position);
String getName=services.getName();
final String getproofing=services.getProofinglink();
final String getsite=services.getSitelink();
proofingLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, Tipster_webview.class);
intent.putExtra("gettproofing_URl",getproofing);
context.startActivity(intent);
}
});
siteLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, Tipster_webview.class);
intent.putExtra("site",getsite);
context.startActivity(intent);
}
});
}
return convertView;
}
TextView proofingLink=(TextView) convertView.findViewById(R.id.txt_proofinglink_tipsterID);
proofingLink.setOnClickListener(new OnItemClickListener() {
#Override
public void onClick(View arg0) {
String url = services.getProofinglink();
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
TextView proofingLink=(TextView)
convertView.findViewById(R.id.txt_proofinglink_tipsterID);
proofingLink.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
TextView siteLink=(TextView)
convertView.findViewById(R.id.txt_sitelink_tipsterID);
siteLink.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});

When i click a list item i want to store it name in an edittext

I am creating an eWallet application like many existing ones. I have lots of classes that do different stuff but i need some advice in a group of them. I have created a listview witch fetches the categories i have created and saved in a phpMyAdmin database. I am displaying this data on a list view successfully. This list view just shows the list of the categories to the user and if he clicks a list item a new activity appers which llows him to edit or delete the list item.
Now i used the same code (i lterally used the same code!) to create a second listview inside a dialog box. Imagine that this listview appears inside the dialog box when i click an edit text which has an on click listener. I successfully display the data in this second list view as well. Now on this dialog box when i click a list item/category (lets say Sports category) i want the name of the edit text to change to the category i chose. But i am confused because i use the same code and methods that open the edit and delete activity on my first list view. I hope i did not confuse you too much.
Here is the code that downloads the data in my list views.
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.ListView;
import android.widget.Toast;
import java.io.BufferedInputStream;
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;
public class ExDownloaderActivity extends AsyncTask<Void, Integer, String>
{
Context context;
String address;
ListView expenseListView;
ProgressDialog progressDialog;
public ExDownloaderActivity(Context context, String address, ListView exCategoryListView)
{
this.context = context;
this.address = address;
this.expenseListView = exCategoryListView;
}
//B4 JOB STARTS
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Fetch Data");
progressDialog.setMessage("Fetching Data...Please wait");
progressDialog.show();
}
#Override
protected String doInBackground(Void... params)
{
String data = downloadData();
return data;
}
#Override
protected void onProgressUpdate(Integer... values)
{
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String string)
{
super.onPostExecute(string);
progressDialog.dismiss();
if(string != null)
{
ExParserActivity parser = new ExParserActivity(context, string, expenseListView);
parser.execute();
}
else
{
Toast.makeText(context, "Unable to download data",Toast.LENGTH_LONG).show();
}
}
private String downloadData()
{
//connect and get a stream of data
InputStream inputStream = null;
//to store each line
String line = null;
try
{
URL url = new URL(address);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
inputStream = new BufferedInputStream(httpURLConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer stringBuffer = new StringBuffer();
if(bufferedReader!= null)
{
while ((line = bufferedReader.readLine()) != null)
{
stringBuffer.append(line + "\n");
}
}
else
{
return null;
}
return stringBuffer.toString();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if(inputStream != null)
{
try
{
inputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
return null;
}
}
Second Class
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class ExParserActivity extends AsyncTask<Void, Integer, Integer>
{
Context context;
ListView exListView;
String data;
ArrayList<String> exCategories = new ArrayList<>();
ProgressDialog progressDialog;
public ExParserActivity(Context context, String data, ListView lv)
{
this.context = context;
this.data = data;
this.exListView = lv;
}
//B4 JOB STARTS
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Parser");
progressDialog.setMessage("Parsing...Please wait");
progressDialog.show();
}
//Heavy job
#Override
protected Integer doInBackground(Void... params)
{
return this.parse();
}
#Override
protected void onProgressUpdate(Integer... values)
{
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Integer integer)
{
super.onPostExecute(integer);
progressDialog.dismiss();
if(integer == 1)
{
//ADAPTER
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, exCategories);
//ADAPT TO LIST VIEW
exListView.setAdapter(arrayAdapter);
//ON CLICK LISTENER
exListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
context.startActivity(new Intent(context, UpdateDeleteExCategories.class));
//Snackbar.make(view, exCategories.get(position), Snackbar.LENGTH_SHORT).show();
}
});
}
else
{
Toast.makeText(context, "Unable to Parse", Toast.LENGTH_LONG).show();
}
}
//PARSE RECEIVED DATA
private int parse()
{
try
{
//ADD THAT DATA TO JSON ARRAY FIRST
JSONArray jsonArray = new JSONArray(data);
//CREATE JO OBJECT TO HOLD A SINGLE ITEM
JSONObject jsonObject = null;
exCategories.clear();
//LOOP THROUGH THE ARRAY
for(int i = 0; i < jsonArray.length(); i++)
{
jsonObject = jsonArray.getJSONObject(i);
//RETRIEVE NAME
String exCatName = jsonObject.getString("exCatName");
//ADD IT TO ARRAY LIST
exCategories.add(exCatName);
}
//IF ITS SUCCESSFUL RETURN 1
return 1;
}
catch (JSONException e)
{
e.printStackTrace();
}
//IF IT IS NOT SUCCESSFUL RETURN 0
return 0;
}
}
Third Class
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.Calendar;
public class AddExpenseActivity extends SwipeFunctionActivity
{
private ImageView backImageView;
private TextView setDateTextView;
private EditText categoryEditText, amountEditText;
int year, month, day;
static final int DIALOG_ID = 0; //Initialise the variable to 0.
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_expense);
final Calendar calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
setDateTextView = (TextView)findViewById(R.id.setDateTextView);
backImageView = (ImageView)findViewById(R.id.backImageView);
categoryEditText = (EditText)findViewById(R.id.categoryEditText);
amountEditText = (EditText)findViewById(R.id.amountEditText);
setDateTextView.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
showDialog(DIALOG_ID);
}
});
categoryEditText.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
pickCategoryMethod();
}
});
backImageView.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
backMethod();
}
});
}
#Override
protected Dialog onCreateDialog(int id)
{
if (id == DIALOG_ID)
{
return new DatePickerDialog(this, dpickerListener, year, month, day);
}
return null;
}
private DatePickerDialog.OnDateSetListener dpickerListener = new DatePickerDialog.OnDateSetListener()
{
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
AddExpenseActivity.this.year = year;
month = monthOfYear + 1;
day = dayOfMonth;
showDate(AddExpenseActivity.this.year, month, day);
//Toast.makeText(AddExpenseActivity.this, "Selected date: " + dayOfMonth + " / " + (monthOfYear+1) + " / " + year, Toast.LENGTH_LONG).show();
}
};
private void showDate(int year, int month, int day)
{
setDateTextView.setText(new StringBuilder().append(day).append("/")
.append(month).append("/").append(year));
}
public void pickCategoryMethod()
{
String url = "http://192.168.0.3/myapp/fexcateg.php";
//
final Dialog dialog = new Dialog(AddExpenseActivity.this);
dialog.setContentView(R.layout.activity_pick_category);
dialog.setTitle(" Pick your Category");
final ListView pickCategoryListView = (ListView)dialog.findViewById(R.id.pickCategoryListView);
final ExDownloaderActivity downloader = new ExDownloaderActivity(this, url, pickCategoryListView);
//Execute download
downloader.execute();
//pickCategoryListView = (ListView)dialog.findViewById(R.id.pickCategoryListView);
//This makes the dialog visible.
dialog.show();
}
public void backMethod()
{
//startActivity(new Intent(getApplicationContext(), BalanceActivity.class));
finish();
}
#Override
public void onSwipeLeft()
{
super.onSwipeLeft();
startActivity(new Intent(getApplicationContext(), AddIncomeActivity.class));
finish();
}
#Override
public void onSwipeRight()
{
super.onSwipeRight();
startActivity(new Intent(getApplicationContext(), AddSavingActivity.class));
finish();
}
}
So for my problem now. I want when i click a category inside the dialog box, the categoryEditText variable i have in the trird class to change in the name of the item i clicked in the listview. First of all where do i have to write this code and secondly how to do it. I am kind of lost becasue is really a big app:/
Many thanks !!!

Listview not displaying the right image in android

In my app I have a listview. Each listview item contains an image view and several textviews. To display the image I use Drawable. But the images are displayed in the wrong row when scrolling. The image in a row changes several times until the right image appears. I have searched the web but I found nothing working for me. I am posting my code below. Please help me! Thanks in advance!
MainActivity.java
package com.makemyandroidapp.example.stacksites;
import java.io.FileNotFoundException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
private SitesAdapter mAdapter;
private ListView sitesList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("StackSites", "OnCreate()");
setContentView(R.layout.activity_main);
//Get reference to our ListView
sitesList = (ListView)findViewById(R.id.sitesList);
//Set the click listener to launch the browser when a row is clicked.
sitesList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int pos,long id) {
String posID = mAdapter.getItem(pos).getID();
Intent i = new Intent(getApplicationContext(), PositionDesc.class);
i.putExtra("posID", posID);
startActivity(i);
}
});
/*
* If network is available download the xml from the Internet.
* If not then try to use the local file from last time.
*/
if(isNetworkAvailable()){
Log.i("StackSites", "starting download Task");
SitesDownloadTask download = new SitesDownloadTask();
download.execute();
}else{
mAdapter = new SitesAdapter(getApplicationContext(), -1, SitesXmlPullParser.getStackSitesFromFile(MainActivity.this, "StackSites.xml"));
sitesList.setAdapter(mAdapter);
}
}
//Helper method to determine if Internet connection is available.
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
/*
* AsyncTask that will download the xml file for us and store it locally.
* After the download is done we'll parse the local file.
*/
private class SitesDownloadTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... arg0) {
//Download the file
try {
Downloader.DownloadFromUrl("https://duapune.com/mobile/listaeplote.php", openFileOutput("StackSites.xml", Context.MODE_PRIVATE));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result){
//setup our Adapter and set it to the ListView.
mAdapter = new SitesAdapter(MainActivity.this, -1, SitesXmlPullParser.getStackSitesFromFile(MainActivity.this, "StackSites.xml"));
sitesList.setAdapter(mAdapter);
Log.i("StackSites", "adapter size = "+ mAdapter.getCount());
}
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
Intent objIntent = new Intent(getApplication(), TabActivity.class);
finish();
startActivity(objIntent);
}
}
SitesAdapter.java
package com.makemyandroidapp.example.stacksites;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
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.RelativeLayout;
import android.widget.TextView;
import android.view.View.OnClickListener;
/*
* Custom Adapter class that is responsible for holding the list of sites after they
* get parsed out of XML and building row views to display them on the screen.
*/
public class SitesAdapter extends ArrayAdapter<StackSite> {
//ImageLoader imageLoader;
//DisplayImageOptions options;
Context c;
String url1;
String url2;
Drawable backgr;
ImageView iconImg;
int posi;
RelativeLayout row;
public SitesAdapter(Context ctx, int textViewResourceId, List<StackSite> sites) {
super(ctx, textViewResourceId, sites);
c=ctx;
}
#Override
public View getView(int pos, View convertView, ViewGroup parent){
posi=pos;
row = (RelativeLayout)convertView;
Log.i("StackSites", "getView pos = " + pos);
if(null == row){
//No recycled View, we have to inflate one.
LayoutInflater inflater = (LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = (RelativeLayout)inflater.inflate(R.layout.row_site, null);
}
//Get our View References
final TextView kompaniaTxt = (TextView)row.findViewById(R.id.nameTxt);
TextView pozicioniTxt = (TextView)row.findViewById(R.id.aboutTxt);
final TextView kategoriaTxt = (TextView)row.findViewById(R.id.kategoriaTxt);
TextView qytetiTxt = (TextView)row.findViewById(R.id.qytetiTxt);
//final ProgressBar indicator = (ProgressBar)row.findViewById(R.id.progress);
kompaniaTxt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//String emri_komp=kompaniaTxt.getText().toString().replaceAll("\\s+","%20");
String emri_komp=kompaniaTxt.getText().toString();
Intent intent=new Intent(c,CompanyDesc.class);
intent.putExtra("emri_komp", emri_komp);
intent.putExtra("url1", url1);
c.startActivity(intent);
}
});
kategoriaTxt.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
String idKateg=getItem(posi).getIdKategoria();
Intent intent=new Intent(c,CategoryList.class);
intent.putExtra("idKateg", idKateg);
intent.putExtra("url2", url2);
c.startActivity(intent);
}
});
//Set the relavent text in our TextViews
kompaniaTxt.setText(getItem(pos).getKompania());
pozicioniTxt.setText(getItem(pos).getPozicioni());
kategoriaTxt.setText(getItem(pos).getKategoria());
qytetiTxt.setText(getItem(pos).getQyteti());
url1=getItem(pos).getImgUrl();
SitesDownloadTask download=new SitesDownloadTask();
download.execute();
return row;
}
private class SitesDownloadTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... arg0) {
try { iconImg = (ImageView)row.findViewById(R.id.iconImg);
backgr=drawable_from_url(url1,"kot");
//backgr=drawable_from_url("https://duapune.com/photos/duapune#duapune.com1349707357.png","kot");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result){
iconImg.setBackground(backgr);
}
Drawable drawable_from_url(String url, String src_name) throws
java.net.MalformedURLException, java.io.IOException
{System.out.println("uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu");
return Drawable.createFromStream(((java.io.InputStream)
new java.net.URL(url.trim()).getContent()), src_name);
}
}
}
Try this..
You have to use ViewHolder for that issue
private class ViewHolder {
ImageView iconImg;
TextView kompaniaTxt,pozicioniTxt,kategoriaTxt,qytetiTxt;
}
EDIT
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder holder;
if (convertView == null) {
view = getActivity().getLayoutInflater().inflate(R.layout.row_site, parent, false);
holder = new ViewHolder();
holder.iconImg = (ImageView) view.findViewById(R.id.iconImg);
holder.kompaniaTxt = (TextView) view.findViewById(R.id.nameTxt);
holder.pozicioniTxt = (TextView) view.findViewById(R.id.aboutTxt);
//holder.kategoriaTxt = (TextView) view.findViewById(R.id.kategoriaTxt);
holder.qytetiTxt = (TextView) view.findViewById(R.id.qytetiTxt);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.kompaniaTxt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//String emri_komp=kompaniaTxt.getText().toString().replaceAll("\\s+","%20");
String emri_komp=holder.kompaniaTxt.getText().toString();
Intent intent=new Intent(c,CompanyDesc.class);
intent.putExtra("emri_komp", emri_komp);
intent.putExtra("url1", url1);
c.startActivity(intent);
}
});
holder.kategoriaTxt.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
String idKateg=getItem(posi).getIdKategoria();
Intent intent=new Intent(c,CategoryList.class);
intent.putExtra("idKateg", idKateg);
intent.putExtra("url2", url2);
c.startActivity(intent);
}
});
//Set the relavent text in our TextViews
holder.kompaniaTxt.setText(getItem(pos).getKompania());
holder.pozicioniTxt.setText(getItem(pos).getPozicioni());
holder.kategoriaTxt.setText(getItem(pos).getKategoria());
holder.qytetiTxt.setText(getItem(pos).getQyteti());
url1=getItem(pos).getImgUrl();
SitesDownloadTask download=new SitesDownloadTask();
download.execute();
return view;
}
and onPostExecute
#Override
protected void onPostExecute(Void result){
holder.iconImg.setBackground(backgr);
}
EDIT
Instead of using SitesDownloadTask AsyncTask use Universal Image Loader lib
https://github.com/nostra13/Android-Universal-Image-Loader
lazy image loader
https://github.com/thest1/LazyList

android + json + how to display the extracted data in a list and when it clicked display the data in a single row?

i am creating a simple android app that get data from a webserver in json type and display it in a listView than when i select a row it must display the specified data in a single row but the problem is that the system show an error to the selected item to display it in the other activity.
can anyone help me ???
the error is in the jsonActivityHttpClient class in the onPostExectute method, it do not take the list "finalResult" neither:
new String[] { PLACE_NAME_TAG, LATITUDE_TAG,LONGITUDE_TAG, POSTAL_CODE_TAG }
JSONParserHandler
package com.devleb.jsonparsingactivitydemo;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.impl.client.BasicResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
public class JSONParserHandler implements ResponseHandler<List<String>> {
public static List<String> finalResult;
public static final String PLACE_NAME_TAG = "placeName";
public static final String LONGITUDE_TAG = "lng";
public static final String LATITUDE_TAG = "lat";
private static final String ADMIN_NAME_TAG = "adminCode3";
public static final String POSTAL_CODE_TAG = "postalcode";
private static final String POSTALCODE = "postalcodes";
#Override
public List<String> handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
// TODO Auto-generated method stub
finalResult = new ArrayList<String>();
String JSONResponse = new BasicResponseHandler()
.handleResponse(response);
try {
JSONObject jsonObject = (JSONObject) new JSONTokener(JSONResponse)
.nextValue();
JSONArray PostalCodes = jsonObject.getJSONArray(POSTALCODE);
for (int i = 0; i < PostalCodes.length(); i++) {
JSONObject postalCode = (JSONObject) PostalCodes.get(i);
String name = postalCode.getString(PLACE_NAME_TAG);
String lat = postalCode.getString(LATITUDE_TAG);
String lng = postalCode.getString(LONGITUDE_TAG);
String postal = postalCode.getString(POSTAL_CODE_TAG);
List<String>tmlResult = new ArrayList<String>();
tmlResult.add(name);
tmlResult.add(lat);
tmlResult.add(lng);
tmlResult.add(postal);
finalResult.addAll(tmlResult);
}
} catch (JSONException E) {
E.printStackTrace();
}
return finalResult;
}
}
JsonActivityHttpClient
package com.devleb.jsonparsingactivitydemo;
import java.io.IOException;
import java.util.List;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import android.app.ListActivity;
import android.content.Intent;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class JsonActivityHttpClient extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new HTTPGetTask().execute();
}
private class HTTPGetTask extends AsyncTask<Void, Void, List<String>> {
private static final String USER_NAME = "devleb";
private static final String URL = "http://api.geonames.org/postalCodeLookupJSON?postalcode=6600&country=AT&username="
+ USER_NAME;
AndroidHttpClient mClient = AndroidHttpClient.newInstance("");
#Override
protected List<String> doInBackground(Void... arg0) {
// TODO Auto-generated method stub
HttpGet request = new HttpGet(URL);
JSONParserHandler responseHandler = new JSONParserHandler();
try {
return mClient.execute(request, responseHandler);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
if (null != mClient) {
mClient.close();
ListAdapter adapter = new SimpleAdapter(
JsonActivityHttpClient.this, finalResult,
R.layout.list_item, new String[] { PLACE_NAME_TAG, LATITUDE_TAG,
LONGITUDE_TAG, POSTAL_CODE_TAG }, new int[] { R.id.countryname,
R.id.lat, R.id.lng, R.id.postalcode });
setListAdapter(adapter);
}
//setListAdapter(new ArrayAdapter<String>(
// JsonActivityHttpClient.this, R.layout.list_item, result));
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.json_activity_http_client, menu);
return true;
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String place_name = ((TextView) v.findViewById(R.id.countryname)).getText().toString();
String lat = ((TextView) v.findViewById(R.id.lat)).getText().toString();
String lng = ((TextView) v.findViewById(R.id.lng)).getText().toString();
String postal_code = ((TextView) v.findViewById(R.id.postalcode)).getText().toString();
Intent in = new Intent(getBaseContext(), RowItem.class);
in.putExtra(PLACE_NAME_TAG, value)
}
}
MainActivity
package com.devleb.jsonparsingactivitydemo;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
final #Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button bntLoad = (Button) findViewById(R.id.btnload);
bntLoad.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
startActivity(new Intent(getBaseContext(), JsonActivityHttpClient.class));
}
}
RowItem
package com.devleb.jsonparsingactivitydemo;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class RowItem extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.row_item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.row_item, menu);
return true;
}
}
i see 2 problem in your code:
1- you define your AsyncTask class like
AsyncTask<Void, Void, List<String>>
but you get Void on onPostExecute method, so you need change
protected void onPostExecute(Void result)
to
protected void onPostExecute(List<String> result)
2- you try access to finalResult on onPostExecute, bu you define that as static on JSONParserHandler so if you want access that you need :
JSONParserHandler.finalResult
but as you return that on doInBackground method so you can access that with:
result
that you get in onPostExecute.
then you need check result that is equal to null or not, because you return null after catch
your onPostExecute must be like:
protected void onPostExecute(List<String> result) {
// TODO Auto-generated method stub
if (null != mClient) {
mClient.close();
if (result != null)
{
ListAdapter adapter = new SimpleAdapter(
JsonActivityHttpClient.this, result,
R.layout.list_item, new String[] { PLACE_NAME_TAG, LATITUDE_TAG,
LONGITUDE_TAG, POSTAL_CODE_TAG }, new int[] { R.id.countryname,
R.id.lat, R.id.lng, R.id.postalcode });
setListAdapter(adapter);
}
else
// do any thing you want for error happened
}

Categories

Resources