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
}
});
Related
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");
}
}
I am developing a MovieApp which loads movie posters in MainActivity Fragment using AsyncTask background thread. I am using gridview and BaseAdapter to display images. Following is the code.
MainActivityFragment.java :
package com.android.example.cinemaapp.app;
import android.app.Fragment;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
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.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
public class MainActivityFragment extends Fragment{
MoviePosterAdapter moviePosterAdapter;
GridView posterGridView;
public HashMap<String, JSONObject> movieMap;
public MainActivityFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onStart(){
super.onStart();
updateMovies();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.moviefragment, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_refresh) {
updateMovies();
}
return super.onOptionsItemSelected(item);
}
public void updateMovies(){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
String sortBy = sharedPreferences.getString(getString(R.string.pref_sort_key), getString(R.string.pref_sort_popular));
new FetchMoviePosterTask().execute(sortBy);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
moviePosterAdapter = new MoviePosterAdapter(getActivity());
posterGridView = (GridView) rootView.findViewById(R.id.gridview_movie);
posterGridView.setAdapter(moviePosterAdapter);
posterGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
// logic to start detail activity
startActivity(intent);
}
});
return rootView;
}
public class FetchMoviePosterTask extends AsyncTask<String, String, Void> implements Serializable {
#Override
protected Void doInBackground(String... params) {
Log.v("FetchMoviePosterTask", "In background method");
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String movieJsonStr;
try {
//logic to create uri builder
URL url = new URL(builtUri.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
movieJsonStr = null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
movieJsonStr = null;
}
movieJsonStr = buffer.toString();
// Log.v("MainActivityFragment", "Movie json "+movieJsonStr);
try {
String[] posterPaths = getPosterPaths(movieJsonStr);
for(String path : posterPaths){
publishProgress(path);
}
}catch(JSONException je){
Log.e("MoviePosterPath","Error while parsing JSON");
}
} catch (IOException e) {
Log.e("MoviePosterAdapter", "Error ", e);
movieJsonStr = null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("MoviePosterAdapter", "Error closing stream", e);
}
}
}
return null;
}
public String[] getPosterPaths(String movieJsonStr) throws JSONException{
final String POSTER_PATH = //some value
final String POSTER_SIZE = //some value
JSONObject jsonObject = new JSONObject(movieJsonStr);
JSONArray results = jsonObject.getJSONArray("results");
String[] posterStrs = new String[results.length()];
movieMap = new HashMap<String, JSONObject>();
for(int i =0; i < results.length(); i++){
JSONObject movieObj = (JSONObject) results.get(i);
posterStrs[i] = POSTER_PATH + POSTER_SIZE + movieObj.getString("poster_path");
movieMap.put(posterStrs[i], movieObj);
}
return posterStrs;
}
#Override
protected void onProgressUpdate(String... posterValues){
Log.v("FetchMoviePosterTask", "In onProgress method");
moviePosterAdapter.add(posterValues[0]);
super.onProgressUpdate(posterValues);
}
#Override
protected void onPostExecute(Void result) {
Log.v("FetchMoviePosterTask", "In onPostExecute method");
moviePosterAdapter.notifyDataSetChanged();
super.onPostExecute(result);
}
}
}
MoviePosterAdapter.java :
package com.android.example.cinemaapp.app;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class MoviePosterAdapter extends BaseAdapter {
ArrayList<String> movieArray = new ArrayList<String>();
private Context mContext;
public MoviePosterAdapter(Context c) {
mContext = c;
}
void add(String path){
movieArray.add(path);
}
void clear(){
movieArray.clear();
}
void remove(int index){
movieArray.remove(index);
}
#Override
public int getCount() {
return movieArray.size();
}
#Override
public Object getItem(int position) {
return movieArray.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
} else {
imageView = (ImageView) convertView;
}
Picasso.with(mContext).load(movieArray.get(position)).into(imageView);
return imageView;
}
}
Problem : When the application is first launched, UI is not getting populated with imageviews. In Logcat I could see control is flowing through doBackground(), onProgressUpdate() and onPostExecute().
When I click 'Refresh' button or If i navigate to some other activity or app and return to Movie app UI (onResume()) it is working perfectly fine. Images are displayed.
Many thanks in advance!
You should change updateMovies(); from onStart() to onCreateView. As Gabe Sechan said, you're wrong about the lifecycle. Try to do some research on the Fragment lifecycle.
Just you need to call method updateMovies(); from onCreateView() after posterGridView = (GridView) rootView.findViewById(R.id.gridview_movie);
remove call from start();
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
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
}
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