I'm currently developing an android application that required to parse an online JSON and display it into custom listview.
My problem is when I run the application it has an error says that
org.json.JSONException: End of input at character 0
Here's what I do:
*layouts/row_listitem.xml*
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="80dp"
android:orientation="vertical"
android:padding="5dp" >
<ImageView
android:id="#+id/iv_icon_social"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_centerVertical="true"
android:background="#drawable/image1"
android:src="#drawable/image1"
android:visibility="gone" />
<LinearLayout
android:id="#+id/thumbnail"
android:layout_width="fill_parent"
android:layout_height="85dp"
android:layout_alignParentRight="true"
android:layout_marginTop="0dp"
android:layout_toRightOf="#+id/iv_icon_social"
android:gravity="center_vertical"
android:orientation="vertical"
android:padding="5dip"
android:visibility="visible" >
<TextView
android:id="#+id/txt_ttlsm_row"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:text="Sample text"
android:textSize="18dp"
android:textStyle="bold" />
<TextView
android:id="#+id/txt_ttlcontact_row2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="0dp"
android:layout_marginTop="3dp"
android:paddingLeft="10dp"
android:maxEms="20"
android:maxLines="2"
android:singleLine="false"
android:ellipsize="end"
android:text="Sample text2"
android:textColor="#808080"
android:textSize="15dp"
android:textStyle="normal"
android:visibility="visible" />
</LinearLayout>
</RelativeLayout>
*layouts/activity_main.xml*
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true" >
</ListView>
</RelativeLayout>
MyBaseAdapter.java
package com.example.parsing_online;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class MyBaseAdapter extends BaseAdapter {
private Activity activity;
private static ArrayList title,notice;
private static LayoutInflater inflater = null;
public MyBaseAdapter(Activity a, ArrayList b, ArrayList bod) {
activity = a;
this.title = b;
this.notice=bod;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi = convertView;
if (convertView == null){
vi = inflater.inflate(R.layout.row_listitem, null);
}
TextView title2 = (TextView) vi.findViewById(R.id.txt_ttlsm_row); // title
String song = title.get(position).toString();
title2.setText(song);
TextView title22 = (TextView) vi.findViewById(R.id.txt_ttlcontact_row2); // notice
String song2 = notice.get(position).toString();
title22.setText(song2);
return vi;
}
}
and in my MainActivity.java
package com.example.parsing_online;
import java.io.IOException;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListView;
public class MainActivity extends Activity {
ArrayList<String> title_array = new ArrayList<String>();
ArrayList<String> notice_array = new ArrayList<String>();
ListView list;
MyBaseAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.listView1);
new TheTask().execute();
}
class TheTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
String str = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://******.com/api/v1/***");
httppost.addHeader("Authorization", "Token token=Wa5sfwP3ku7c15qkZTsdSA");
HttpResponse response = httpclient.execute(httppost);
str = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
String response = result.toString();
try {
JSONArray new_array = new JSONArray(response);
for (int i = 0, count = new_array.length(); i < count; i++) {
try {
JSONObject jsonObject = new_array.getJSONObject(i);
title_array.add(jsonObject.getString("title").toString());
notice_array.add(jsonObject.getString("notice").toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter = new MyBaseAdapter(MainActivity.this, title_array, notice_array);
list.setAdapter(adapter);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Just check the json. I think its not a valid one.Just try with below one
{
"id": "4",
"title": "Test",
"notice": "Test"
}
Related
I want to make listView element clickable.
When i add gridView inside listView then i cant click on listView element..
How to make listView element clickable when gridView is inside listView?
I try to set focusable, descendantFocusability, clickable...
ProductsFragment.java
package pl.pieczolap.ui.products;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;
import pl.globoox.pieczolap.R;
import pl.pieczolap.API.getProducts;
import pl.pieczolap.MyGridView;
public class ProductsFragment extends Fragment {
private ProductsViewModel StampViewModel;
ArrayList<String> product_uid_shop = new ArrayList();
ArrayList<String> product_uid_product = new ArrayList();
ArrayList<String> product_name = new ArrayList();
ArrayList<String> product_info = new ArrayList();
ArrayList<String> product_stamps = new ArrayList();
ArrayList<String> product_clientStamps = new ArrayList();
MyGridView gridView_stamps;
ListView listView_products;
SharedPreferences sharedPref;
Integer clientStamps;
Integer needStamps;
ImageView imageView_loadingData;
TextView textView_winner;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
StampViewModel =
ViewModelProviders.of(this).get(ProductsViewModel.class);
View root = inflater.inflate(R.layout.fragment_products, container, false);
// LOAD GIF LOADING IMAGE
imageView_loadingData = root.findViewById(R.id.imageView_loadingData);
Glide.with(root).load(R.drawable.loadingdots).placeholder(R.drawable.loadingdots).into(imageView_loadingData);
listView_products = root.findViewById(R.id.listView_products);
sharedPref = getActivity().getApplicationContext().getSharedPreferences("pl.piecozlap", Context.MODE_PRIVATE);
Bundle arguments = this.getArguments();
String uid_shop = arguments.getString("uid_shop", "none");
// GET ALL STAMPS
Response.Listener<String> responseListenerUserComments = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
int errorCode = jsonResponse.getInt("errorCode");
// CANT CONNECT TO DATABASE
if (errorCode == 1) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity().getApplicationContext());
builder.setMessage("Brak połączenia z bazą danych!").setNegativeButton("PONÓW", null).create().show();
}
// GET STAMP AND PRODUCT INFO
if (errorCode == 2) {
JSONArray products = jsonResponse.getJSONArray("products");
for (int i = 0; i < products.length(); i++) {
JSONObject jsonObject = products.getJSONObject(i);
product_uid_shop.add(jsonObject.getString("uid_shop"));
product_uid_product.add(jsonObject.getString("uid_product"));
product_name.add(jsonObject.getString("name"));
product_info.add(jsonObject.getString("info"));
product_stamps.add(jsonObject.getString("stamps"));
product_clientStamps.add(jsonObject.getString("clientStamps"));
}
// HIDE LOADING GIF
imageView_loadingData.setVisibility(View.INVISIBLE);
ProductsAdapter productsAdapter = new ProductsAdapter();
listView_products.setAdapter(productsAdapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
getProducts getStamps = new getProducts(sharedPref.getString("uid_client", "none"), uid_shop, responseListenerUserComments);
RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
queue.add(getStamps);
return root;
}
// LISTVIEW CUSTOMADAPTER
// LISTVIEW CUSTOMADAPTER
// LISTVIEW CUSTOMADAPTER
// LISTVIEW CUSTOMADAPTER
public class ProductsAdapter extends BaseAdapter {
#Override
public int getCount() {
return product_uid_shop.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
convertView = getLayoutInflater().inflate(R.layout.customlayout_products, null);
clientStamps = Integer.valueOf(product_clientStamps.get(position));
needStamps = Integer.valueOf(product_stamps.get(position));
TextView textView_product_name = convertView.findViewById(R.id.textView_product_name);
TextView textView_product_info = convertView.findViewById(R.id.textView_product_info);
textView_product_name.setText(String.valueOf(clientStamps));
textView_product_info.setText(product_info.get(position));
// WINNER TEXTVIEW
TextView textView_winner = convertView.findViewById(R.id.textView_winner);
if (clientStamps == needStamps) {
textView_winner.setVisibility(View.VISIBLE);
} else {
textView_winner.setVisibility(View.INVISIBLE);
}
// -------------------- //
// CLICK ON SHOP //
// -------------------- //
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("TAGA", "sasdadsa");
new AlertDialog.Builder(getActivity().getApplicationContext())
.setTitle("Delete entry")
.setMessage("Are you sure you want to delete this entry?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Continue with delete operation
}
})
.setNegativeButton(android.R.string.no, null)
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
});
gridView_stamps = convertView.findViewById(R.id.gridView_stamps);
StampsAdapter stampAdapter = new StampsAdapter();
gridView_stamps.setAdapter(stampAdapter);
gridView_stamps.setClickable(false);
return convertView;
}
}
// STAMP GRIDVIEW
// STAMP GRIDVIEW
// STAMP GRIDVIEW
// STAMP GRIDVIEW
public class StampsAdapter extends BaseAdapter {
#Override
public int getCount() {
return needStamps;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = getLayoutInflater().inflate(R.layout.customlayout_onestamp, null);
if (position < clientStamps) {
final ImageView imageView = convertView.findViewById(R.id.imgageView_onestamp);
Picasso.get().load("http://pieczolap.pl/admin/shops/999/stamp.jpg").into(imageView);
}
return convertView;
}
}
}
customlayout_products.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="400dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="50dp"
android:background="#drawable/customlayout_shops_background"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:background="#drawable/customlayout_shops_background">
<TextView
android:id="#+id/textView_product_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="Info"
android:textSize="15dp" />
<TextView
android:id="#+id/textView_product_info"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/textView_product_name"
android:layout_margin="5dp"
android:text="Info"
android:textSize="10dp" />
</RelativeLayout>
<pl.pieczolap.MyGridView
android:id="#+id/gridView_stamps"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:clickable="false"
android:columnWidth="100dp"
android:gravity="center"
android:horizontalSpacing="10dp"
android:numColumns="4"
android:padding="10dp"
android:stretchMode="spacingWidth"
android:verticalSpacing="10dp"
app:layout_constraintTop_toBottomOf="#id/relativeLayout"
tools:ignore="MissingConstraints" />
<TextView
android:id="#+id/textView_winner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:gravity="center"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:rotation="-6"
android:layout_margin="5dp"
android:textColor="#FF0000"
android:textStyle="bold"
android:text="Zebrano wszystkie!"
android:textSize="30dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
fragment_products.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:descendantFocusability="blocksDescendants"
android:focusable="true"
android:layout_height="match_parent">
<ListView
android:id="#+id/listView_products"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants"
android:divider="#null"
android:focusable="true"
android:clickable="true"
android:dividerHeight="10dp"
android:padding="4dp"
android:layout_marginBottom="70dp"
app:layout_constraintTop_toBottomOf="#+id/button_addShop" />
<ImageView
android:id="#+id/imageView_loadingData"
android:layout_width="350dp"
android:layout_height="100dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
I have a gridview which is supposed to contain an image and a text below it. I am using Picasso to load the images but when I run the app, nothing appears in the imageviews!
Below is my MainActivity.java code:
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity {
GridView gv;
Context context;
ArrayList prgmName;
public static String [] prgmNameList={"C++","VB.NET","JAVA", "JavaScript", "MySQL", "PHP"};
public static String [] prgmImgFiles = {"cpp.png", "vb.net.png", "java.png", "js.png", "mysql.png", "php.png"};
public static Integer [] prgmImages={R.mipmap.img_0, R.mipmap.img_1, R.mipmap.img_2};
public ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(prgmNameList));
public ArrayList<Integer> arrayList2 = new ArrayList<Integer>(Arrays.asList(prgmImages));
public ArrayList<String> arrayList3 = new ArrayList<String>(Arrays.asList(prgmImgFiles));
public static GridViewAdapter gvd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onLoadClick(View v)
{
gv=(GridView) findViewById(R.id.gridView2);
gvd = new GridViewAdapter(this, arrayList, arrayList3);
gv.setAdapter(gvd);
ImageView iv2 = (ImageView)findViewById(R.id.imageViewTest);
// addItem("JavaScript", "http://10.0.2.2/picgal/images/js.png");
Picasso.with(this).load("http://10.0.2.2/picgal/images/java.png").into(iv2);
}
public void addItem(String txt, String ImgID)
{
arrayList.add(txt);
arrayList3.add(ImgID);
gvd.notifyDataSetChanged();
}
}
Below is my GridViewAdapter.java code:
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
/**
* Created by ITM on 7/4/2016.
*/
public class GridViewAdapter extends BaseAdapter {
ArrayList<String> result;
Context context;
ArrayList<String> imageId;
private static LayoutInflater inflater=null;
public static final String server = "http://10.0.2.2/picgal/images/";
public Holder holder=new Holder();
public GridViewAdapter(MainActivity mainActivity, ArrayList<String> prgmNameList, ArrayList<String> prgmImages) {
// TODO Auto-generated constructor stub
result=prgmNameList;
context=mainActivity;
imageId=prgmImages;
inflater = ( LayoutInflater )context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return result.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;
}
public class Holder
{
public TextView tv;
public ImageView img;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View rowView;
rowView = inflater.inflate(R.layout.img_layout, null);
holder.tv=(TextView) rowView.findViewById(R.id.txt);
holder.img=(ImageView) rowView.findViewById(R.id.img);
holder.tv.setText(result.get(position));
Log.i("getView", imageId.get(position));
Picasso.with(context).load(imageId.get(position)).into(holder.img);
// holder.img.setImageResource(imageId.get(position));
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "You Clicked " + result.get(position) +"\n"+getCount(), Toast.LENGTH_LONG).show();
}
});
return rowView;
}
}
The activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.badihbarakat.gridviewapp.MainActivity">
<GridView
android:layout_width="wrap_content"
android:layout_height="250dp"
android:id="#+id/gridView2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:background="#ffe5e5"
android:columnWidth="100dp"
android:drawSelectorOnTop="true"
android:gravity="center"
android:numColumns="auto_fit"
android:stretchMode="spacingWidthUniform"
android:verticalSpacing="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:scrollIndicators="left" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Load"
android:id="#+id/btnLoad"
android:layout_below="#+id/gridView2"
android:layout_centerHorizontal="true"
android:onClick="onLoadClick" />
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/imageViewTest"
android:layout_below="#+id/btnLoad"
android:layout_centerHorizontal="true" />
</RelativeLayout>
The img_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true">
<ImageView
android:id="#+id/img"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/frame" />
</FrameLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/txt"
android:textAlignment="center"/>
</LinearLayout>
I have added a test ImageView below the button to test the Picasso object working. It is working fine. Can any one help please.
Thanks
1.You are passing wrong arguments in the gridView's constructor.
gvd = new GridViewAdapter(this, arrayList, arrayList3);
should be
gvd = new GridViewAdapter(this, arrayList, arrayList2);
as stated in your code, arrayList2 consists of Images.
2.In adapter, change the second argument in constructor:
from ArrayList<String> to ArrayList<Integer>
public GridViewAdapter(MainActivity mainActivity, ArrayList<String> prgmNameList, ArrayList<Integer> prgmImages) {
//...
}
After this, try passing it to Picasso.
New :
Can you try the following code :
//server url
String imageURL = ""
//array of images passed in constructor to append with url
String arrayOfImages[] = imageId;
String completeImageURL = server + arrayOfImages[position];
Picasso.with(context)
.load(completeImageURL)
.into(holder.img);
Best ever I used , ImageLoader Library
https://github.com/nostra13/Android-Universal-Image-Loader
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(imageUri, imageView);
Thanks for all of you who assisted in this question.
Actually, after revising the Picasso code, I discovered that the path to the image file was missing!
What I have put was:
Picasso.with(context).load(imageId.get(position)).into(holder.img);
As imageId.get(position) contains only the file name and not the full path on the server, the Picasso was not able to find the file!
The correct code is:
Picasso.with(context).load(server+imageId.get(position)).into(holder.img);
Where server is a String containing the full path of the images folder.
Thanks again to all of you.
Am using the following code. Every time on logcat am getting the dialogue ad is not visible. not refreshing. And the ad is not showing but the same thing is working fine when am using it with out the help of a fragments.
Somebody please tell me whats worng with my code.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ll1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
>
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="4"
android:gravity="center"
>
<TextView
android:id="#+id/textView1"
android:layout_marginLeft="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
/>
<Button
android:id="#+id/Button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="3"
android:paddingRight="5dp"
android:layout_marginRight="15dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:background="#android:color/transparent"
/>
</LinearLayout>
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="250dp"
/>
<TextView
android:id="#+id/textView4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:paddingRight="5dp"
/>
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="15dp"
android:paddingRight="10dp"
android:text=""
/>
<TextView
android:id="#+id/textView5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:paddingRight="5dp"
/>
<TextView
android:id="#+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="15dp"
android:paddingRight="10dp"
/>
<com.google.android.gms.ads.AdView
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="#+id/adView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
ads:adSize="BANNER"
ads:adUnitId="xxxxxxxxxxxxxxxxxxxxxxx" />
</LinearLayout>
</ScrollView>
</RelativeLayout>
java code
package com.xx.xx;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.HttpResponse;
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.json.JSONArray;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
public class DetailsFragment extends Fragment {
public DetailsFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_details, container, false);
return rootView;
}
ListView list;
Lazyimg adapter;
String name,imageurl,description,ingradiants,tduration;
String[] mname,mimageurl;
private ProgressDialog dialog;
String ids,b1status;
Button b1;
private static Typeface typeFace = null;
private static Typeface itypeFace = null;
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
AdView adView = (AdView) getActivity().findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
b1=(Button)getActivity().findViewById(R.id.Button1);
ids= getArguments().getString("ids");
ids=ids.replace(" ", "%20");
ids=ids.replace("-", "%27");
initTypeFace(getActivity());
iinitTypeFace(getActivity());
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
GetData obj = new GetData();
dialog = ProgressDialog.show(getActivity(), "",
"Please wait...", true);
TelephonyManager tManager = (TelephonyManager) getActivity().getBaseContext()
.getSystemService(Context.TELEPHONY_SERVICE);
String deviceIMEI = tManager.getDeviceId();
String urls="cczczccxx/xxy.php?id="+ids+"&imei="+deviceIMEI+"&fav=jomin";
obj.execute(urls);
}
});
loadingPopup();
}
private void loadingPopup() {
GetData obj = new GetData();
dialog = ProgressDialog.show(getActivity(), "",
"Loading recipe details...", true);
TelephonyManager tManager = (TelephonyManager) getActivity().getBaseContext()
.getSystemService(Context.TELEPHONY_SERVICE);
String deviceIMEI = tManager.getDeviceId();
String urls="xxx/xxy.php?id="+ids+"&imei="+deviceIMEI;
obj.execute(urls);
}
public class GetData extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
BufferedReader reader =null;
String data =null;
try{
HttpClient client = new DefaultHttpClient();
URI uri=new URI(params[0]);
HttpGet get =new HttpGet(uri);
HttpResponse response= client.execute(get);
InputStream stream=response.getEntity().getContent();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer =new StringBuffer("");
String line="";
while((line=reader.readLine())!=null){
buffer.append(line);
}
reader.close();
data = buffer.toString();
JSONObject fulldata = new JSONObject(data);
JSONArray albumdata = (JSONArray) fulldata.get("data");
JSONObject sobj = null;
name=""; imageurl=""; description=""; ingradiants=""; tduration=""; b1status="";
for(int j=0;j<albumdata.length();++j)
{
sobj= (JSONObject) albumdata.get(j);
b1status += (String)sobj.get("fav");
name += (String) sobj.get("name");
imageurl += (String) sobj.get("imageurl");
description += (String) sobj.get("description");
ingradiants += (String) sobj.get("ingradiants");
tduration += (String) sobj.get("tduration");
}
return "";
}
catch(URISyntaxException e){
e.printStackTrace();
}
catch(ClientProtocolException f){
f.printStackTrace();
}
catch(IOException g){
g.printStackTrace();
}
catch(Exception e)
{
//
}
finally{
if(reader!=null){
try{
reader.close();
}
catch(Exception e){
}
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
try {
dialog.dismiss();
} catch (Exception e) {
Log.e(e.getClass().getName(), e.getMessage(), e);
}
if(result==null)
{
new AlertDialog.Builder(getActivity())
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage("\n Connection Error..!\n")
.setPositiveButton("Exit", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
getActivity().finish();
}
})
.setNegativeButton("Retry", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialoga, int which) {
try {
dialog.dismiss();
} catch (Exception e) {
Log.e(e.getClass().getName(), e.getMessage(), e);
}
GetData obj = new GetData();
dialog = ProgressDialog.show(getActivity(), "",
"Loading recipe details...", true);
TelephonyManager tManager = (TelephonyManager) getActivity().getBaseContext()
.getSystemService(Context.TELEPHONY_SERVICE);
String deviceIMEI = tManager.getDeviceId();
String urls="xxxxy.php?id="+ids+"&imei="+deviceIMEI;
obj.execute(urls);
}
})
.show();
}
else
{
mname = name.split("xstream");
mimageurl = imageurl.split("xstream");
if(b1status.equals(""))
{
b1.setBackgroundResource(R.drawable.favr);
}
else if(b1status.equals("f"))
{
b1.setBackgroundResource(R.drawable.favrg);
}
TextView ting=(TextView)getView().findViewById(R.id.textView4);
ting.setText("Ingredients");
ting.setTypeface(typeFace);
ting.setTextColor(Color.parseColor("#210B61"));
ting.setTextSize(25);
TextView tpre=(TextView)getView().findViewById(R.id.textView5);
tpre.setText("\n\nDirections for Preparation");
tpre.setTypeface(typeFace);
tpre.setTextColor(Color.parseColor("#210B61"));
tpre.setTextSize(25);
if(tduration.equals(""))
{
TextView ttduration=(TextView)getView().findViewById(R.id.textView1);
ttduration.setText("READY IN : Depends");
ttduration.setTypeface(itypeFace);
ttduration.setTextColor(Color.parseColor("#FF8000"));
ttduration.setTextSize(20);
}
else
{
TextView ttduration=(TextView)getView().findViewById(R.id.textView1);
ttduration.setText("READY IN : "+tduration);
ttduration.setTypeface(itypeFace);
ttduration.setTextColor(Color.parseColor("#FF8000"));
ttduration.setTextSize(20);
}
TextView tingradiants=(TextView)getView().findViewById(R.id.textView2);
ingradiants=ingradiants.replaceAll("<br>", "\n\n");
ingradiants=ingradiants.replaceAll(""", "\"");
ingradiants=ingradiants.replaceAll("'", "'");
ingradiants=ingradiants.replaceAll("®", " ");
tingradiants.setText(ingradiants);
tingradiants.setTypeface(typeFace);
tingradiants.setTextColor(Color.parseColor("#000000"));
tingradiants.setTextSize(20);
TextView tdescription=(TextView)getView().findViewById(R.id.textView3);
description=description.replaceAll("<br>", "\n\n");
description=description.replaceAll(""", "\"");
description=description.replaceAll("'", "'");
description=description.replaceAll("®", " ");
tdescription.setText(description);
tdescription.setTypeface(itypeFace);
tdescription.setTextSize(20);
list=(ListView)getView().findViewById(R.id.list);
// Create custom adapter for listview
adapter=new Lazyimg(getActivity(), mimageurl,mname);
//Set adapter to listview
list.setAdapter(adapter);
}
//Button b=(Button)findViewById(R.id.button1);
//b.setOnClickListener(listener);
}
}
public static void initTypeFace(Context context) {
try {
typeFace = Typeface.createFromAsset(context.getAssets(), "Nexa_Light.otf");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void iinitTypeFace(Context context) {
try {
itypeFace = Typeface.createFromAsset(context.getAssets(), "iowan.ttf");
} catch (Exception e) {
e.printStackTrace();
}
}
}
It could be as simple as your AdView not actually being on screen. The AdView is contained within a ScrollView so there is no guarantee that it is actually on screen.
You have a complicated view hierarchy. Suggest you simplify it and move the AdView outside of your ScrollView.
Hereby i have design this activity, My data from webservice is properly working, but i can't get the dropdownlist. here i convert the arraylist into String array for show the result in autocomplete.Kindly help me. Thanks in Advance.
File:proprety.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/menubar12"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="left|center_vertical"
android:background="#drawable/property_header"
android:gravity="left|center"
android:orientation="horizontal" >
<Button
android:id="#+id/btn_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:background="#drawable/home"
android:onClick="myclick_home" />
<LinearLayout
android:id="#+id/menubar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="right|center"
android:orientation="horizontal" >
<Button
android:id="#+id/btn_logout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:background="#drawable/logout"
android:onClick="myclick_logout" />
</LinearLayout>
</LinearLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:id="#+id/bg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:orientation="vertical" >
<AutoCompleteTextView
android:id="#+id/et_propertyact_propertyname"
android:layout_width="match_parent"
android:layout_height="28dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="10dp"
android:background="#drawable/property_text"
android:cursorVisible="true"
android:ems="10"
android:hint="Property Name"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:singleLine="true"
android:textColor="#ffffff"
android:textColorHint="#ffffff"
android:textSize="14sp"
android:textStyle="bold" >
<requestFocus />
</AutoCompleteTextView>
<AutoCompleteTextView
android:id="#+id/et_propertyact_blockname"
android:layout_width="match_parent"
android:layout_height="28dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="10dp"
android:background="#drawable/block_text"
android:cursorVisible="true"
android:ems="10"
android:hint="Block Name"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:singleLine="true"
android:textColor="#ffffff"
android:textColorHint="#ffffff"
android:textSize="14sp"
android:textStyle="bold" >
</AutoCompleteTextView>
<AutoCompleteTextView
android:id="#+id/et_propertyact_appartmentname"
android:layout_width="match_parent"
android:layout_height="28dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="10dp"
android:background="#drawable/apartment"
android:cursorVisible="true"
android:ems="10"
android:hint="Apartment Name"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:singleLine="true"
android:textColor="#ffffff"
android:textColorHint="#ffffff"
android:textSize="14sp"
android:textStyle="bold" >
</AutoCompleteTextView>
<LinearLayout
android:id="#+id/bg_buttons"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:gravity="center"
android:orientation="vertical"
android:padding="5dp" >
<Button
android:id="#+id/btn_propertyact_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/view_button" />
</LinearLayout>
</LinearLayout>
</ScrollView>
<ListView
android:id="#+id/property_listView"
android:layout_width="wrap_content"
android:layout_height="0dip"
android:layout_marginLeft="6dp"
android:layout_marginRight="6dp"
android:layout_marginTop="6dp"
android:layout_weight="1"
android:cacheColorHint="#00000000"
android:clickable="true"
android:divider="#drawable/cellborder" android:dividerHeight="1dp" android:focusable="true" >
</ListView>
</LinearLayout>
File:PropertyActivity.Java
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONObject;
import com.example.webservice.JSONfunction_JSONArray;
import com.example.webservice.JSONfunction_JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.MultiAutoCompleteTextView;
import android.widget.SimpleAdapter;
public class PropertyActivity extends Activity {
/* ====Components Declaration Part Begins here======= */
private ListView property_listView;
private ListView list_property;
private Button btn_view;
private AutoCompleteTextView propertyname, blockname, apartmentname;
private static final String TAG = "AppSquare";
/* ====ServiceVariables Declarations Part ======= */
JSONArray j_array,j_array1;
JSONObject j_obj,j_obj1;
ArrayList<HashMap<String, String>> arrList_proprty_list = new ArrayList<HashMap<String, String>>();
public static ArrayList<String> arrList_property_names = new ArrayList<String>();
public static ArrayList<String> arrList_block_names = new ArrayList<String>();
public static ArrayList<String> arrList_apartment_names = new ArrayList<String>();
public static ArrayList<String> arrList_property_names_id= new ArrayList<String>();
public static ArrayList<String> arrList_block_names_id= new ArrayList<String>();
public static ArrayList<String> arrList_apartment_names_id= new ArrayList<String>();
private ArrayAdapter<String> PropAdapter;
private ArrayAdapter<String> BlockAdapter;
private ArrayAdapter<String> ApartmentAdapter;
public static String[] arr_Prop_name;
public static String[] arr_block_name;
public static String[] arr_apartment_name;
/* ====API Declarations Part ======= */
public static final String ip = "192.168.0.6";
String API_propSelect = "http://" + ip + "/APP2/propertySelect.php";
String API_blockSelect = "http://" + ip + "/APP2/blockSelect.php";
String API_apartmentSelect = "http://" + ip + "/APP2/apartmentSelect.php";
String API_propDetails = "http://" + ip + "/App2/propertyDetails.php";
/* ====OnClick Declarations Part ======= */
/* ====OnClick Definition Part Begins here======= */
public void myclick_logout(View v) {
AlertDialog.Builder builder2 = new AlertDialog.Builder(
PropertyActivity.this);
builder2.setTitle("Warning");
builder2.setMessage("Closing Application..");
builder2.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// finish();
// System.exit(0);
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
finish();
}
});
builder2.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder2.show();
}
public void myclick_home(View v) {
startActivity(new Intent(PropertyActivity.this, DashBoardActivity.class));
}
/* ====OnCreate Definition Part Begins here======= */
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.property_activity);
getPrefernces();
new PropName().execute();
new BlockName().execute();
new ApartmentName().execute();
setValue_AutoComplete();
Viewbtn_action();
}
public void getPrefernces()
{
property_listView = (ListView) findViewById(R.id.property_listView);
propertyname = (AutoCompleteTextView) findViewById(R.id.et_propertyact_propertyname);
blockname = (AutoCompleteTextView) findViewById(R.id.et_propertyact_blockname);
apartmentname = (AutoCompleteTextView) findViewById(R.id.et_propertyact_appartmentname);
btn_view = (Button) findViewById(R.id.btn_propertyact_view);
}
public void setValue_AutoComplete()
{
/*-------Load Data into PropertList-----*/
arr_Prop_name = arrList_property_names.toArray(new String[arrList_property_names.size()]);
PropAdapter = new ArrayAdapter<String>(PropertyActivity.this,android.R.layout.simple_dropdown_item_1line,arr_Prop_name);
propertyname.setAdapter(PropAdapter);
propertyname.getDropDownBackground().setAlpha(255);
propertyname.setThreshold(1);
/*------Load Data into Block List------*/
arr_block_name = arrList_block_names.toArray(new String[arrList_block_names.size()]);
BlockAdapter = new ArrayAdapter<String>(PropertyActivity.this,android.R.layout.simple_dropdown_item_1line,arr_block_name);
blockname.setAdapter(BlockAdapter);
blockname.getDropDownBackground().setAlpha(255);
blockname.setThreshold(1);
/*------Load Data into apartment List------*/
arr_apartment_name = arrList_apartment_names.toArray(new String[arrList_apartment_names.size()]);
ApartmentAdapter = new ArrayAdapter<String>(PropertyActivity.this,android.R.layout.simple_dropdown_item_1line,arr_apartment_name);
apartmentname.setAdapter(ApartmentAdapter);
apartmentname.getDropDownBackground().setAlpha(255);
apartmentname.setThreshold(1);
}
private void Viewbtn_action() {
btn_view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
class PropName extends AsyncTask<Void, Void, String>
{
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
try{
System.out.println("In Background...PropName");
System.out.println(API_propSelect);
j_obj=JSONfunction_JSONObject.getJSONfromURL(API_propSelect);
Log.d(TAG, "JSON_RES" + j_obj);
j_array = j_obj.getJSONArray("property");
for (int i = 0; i < j_array.length(); i++)
{
j_obj1 = j_array.getJSONObject(i);
String id= j_obj1.getString("Id");
String value=j_obj1.getString("Value");
System.out.println("Id------>"+id);
System.out.println("Value------>"+value);
//arrList_property_names_id.add(id);
arrList_property_names.add(value);
//System.out.println("Value in array list------>"+arrList_property_names_id);
System.out.println("Value in array list------>"+arrList_property_names);
}
} catch (Exception e) {
Log.d("Error", "Error in API" + e.getStackTrace().toString());
}
return "";
}
}
class BlockName extends AsyncTask<Void, Void, String>
{
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
try{
System.out.println("In Background...BlockName");
System.out.println(API_blockSelect);
j_obj=JSONfunction_JSONObject.getJSONfromURL(API_blockSelect);
Log.d(TAG, "JSON_RES" + j_obj);
j_array = j_obj.getJSONArray("apartment");
for (int i = 0; i < j_array.length(); i++)
{
j_obj1 = j_array.getJSONObject(i);
String id= j_obj1.getString("Id");
String value=j_obj1.getString("Value");
System.out.println("Id------>"+id);
System.out.println("Value------>"+value);
//arrList_block_names_id.add(id);
arrList_block_names.add(value);
//System.out.println("Value in array list------>"+arrList_block_names_id);
System.out.println("Value in array list------>"+arrList_block_names);
}
} catch (Exception e) {
Log.d("Error", "Error in API" + e.getStackTrace().toString());
}
return "";
}
}
class ApartmentName extends AsyncTask<Void, Void, String>
{
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
try{
System.out.println("In Background...ApartmentName");
System.out.println(API_apartmentSelect);
j_obj=JSONfunction_JSONObject.getJSONfromURL(API_apartmentSelect);
Log.d(TAG, "JSON_RES" + j_obj);
j_array = j_obj.getJSONArray("block");
for (int i = 0; i < j_array.length(); i++)
{
j_obj1 = j_array.getJSONObject(i);
String id= j_obj1.getString("Id");
String value=j_obj1.getString("Value");
System.out.println("Id------>"+id);
System.out.println("Value------>"+value);
//arrList_apartment_names_id.add(id);
arrList_apartment_names.add(value);
//System.out.println("Value in array list------>"+arrList_apartment_names_id);
System.out.println("Value in array list------>"+arrList_apartment_names);
}
} catch (Exception e) {
Log.d("Error", "Error in API" + e.getStackTrace().toString());
}
return "";
}
}
}
Finally got answer
1.Implements Texwatcher
2.override the OnTextChanged();
Thats it...
public class PropertyActivity extends Activity implements TextWatcher{
#Override
protected void onCreate(Bundle savedInstanceState) {
propertyname = (AutoCompleteTextView) findViewById(R.id.et_propertyact_propertyname);
propertyname.addTextChangedListener(this);
blockname = (AutoCompleteTextView) findViewById(R.id.et_propertyact_blockname);
blockname.addTextChangedListener(this);
apartmentname = (AutoCompleteTextView) findViewById(R.id.et_propertyact_appartmentname);
apartmentname.addTextChangedListener(this);
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
PropAdapter = new ArrayAdapter<String>(PropertyActivity.this,R.layout.my_autolist_item,arr_Prop_name);
// propertyname.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
propertyname.getDropDownBackground().setAlpha(255);
propertyname.setThreshold(1);
propertyname.setAdapter(PropAdapter);
BlockAdapter = new ArrayAdapter<String>(PropertyActivity.this,R.layout.my_autolist_item,arr_block_name);
// blockname.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
blockname.getDropDownBackground().setAlpha(255);
blockname.setThreshold(1);
blockname.setAdapter(BlockAdapter);
ApartmentAdapter = new ArrayAdapter<String>(PropertyActivity.this,R.layout.my_autolist_item,arr_apartment_name);
// apartmentname.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
apartmentname.getDropDownBackground().setAlpha(255);
apartmentname.setThreshold(1);
apartmentname.setAdapter(ApartmentAdapter);
}
}
I have made a ListView in that every ListItem is having EditText ,I want to edit them,But I am not able to edit them,Please help me for that,My code is as below,I have mentioned my java class(activity),Xml and raw file which will be binded to the ListView and adapter:
cart.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<RelativeLayout
android:id="#+id/hdr_cart"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/header_bg" />
<TextView
android:id="#+id/tv_title"
style="#style/font_med"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="My cart"
android:textColor="#ff0000" />
<ImageView
android:id="#+id/iv_bak"
style="#style/iv_buyingrequest"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:background="#drawable/btn_back" />
</RelativeLayout>
<ListView
android:id="#+id/cart_list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/tv_total"
android:layout_below="#+id/hdr_cart" />
<TextView
android:id="#+id/tv_total"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/ll_botom"
android:layout_alignParentLeft="true"
android:layout_marginLeft="5dp"
android:padding="5dp"
android:text="Total:"
android:textSize="20dp" />
<LinearLayout
android:id="#+id/ll_botom"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:orientation="horizontal"
android:weightSum="2" >
<Button
android:id="#+id/tv_place_order"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/bg_blu_btn_selector"
android:gravity="center"
android:padding="8dp"
android:text="Place Order"
android:textColor="#ffffff"
android:textSize="16dp"
android:textStyle="bold" />
<Button
android:id="#+id/tv_home"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/bg_blu_btn_selector"
android:gravity="center"
android:padding="8dp"
android:text="Continue Shopping"
android:textColor="#ffffff"
android:textSize="16dp"
android:textStyle="bold" />
</LinearLayout>
</RelativeLayout>
raw.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:descendantFocusability="blocksDescendants"
android:padding="10dp" >
<ImageView
android:id="#+id/iv_product_img"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_gravity="left"
android:layout_marginTop="5dp" />
<TextView
android:id="#+id/product_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#+id/iv_product_img"
android:paddingBottom="5dp"
android:paddingTop="5dp"
android:text="product Name"
android:textColor="#545454"
android:textSize="14dp"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_qty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/product_label"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#+id/iv_product_img"
android:text="Quantity:"
android:textColor="#000000"
android:textSize="12dp" />
<EditText
android:id="#+id/et_qty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/product_label"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#+id/tv_qty"
android:background="#drawable/blk_editext"
android:ems="4"
android:gravity="center_vertical"
android:text="200"
android:textSize="12dp" />
<TextView
android:id="#+id/tv_unit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/product_label"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#+id/et_qty"
android:text="Acre"
android:textColor="#000000"
android:textSize="12dp" />
<TextView
android:id="#+id/tv_wholesale_proce"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/et_qty"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#+id/iv_product_img"
android:text="Price:"
android:textColor="#000000"
android:textSize="12dp" />
<TextView
android:id="#+id/tv_wprice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/et_qty"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#+id/tv_wholesale_proce"
android:text="100"
android:textColor="#545454"
android:textSize="12dp" />
<TextView
android:id="#+id/tv_retail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tv_wprice"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#+id/iv_product_img"
android:text="Sub Total:"
android:textColor="#000000"
android:textSize="12dp" />
<TextView
android:id="#+id/tv_rprice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tv_wprice"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#+id/tv_retail"
android:text="100"
android:textColor="#545454"
android:textSize="12dp" />
<TextView
android:id="#+id/pro_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/min_qty"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#+id/fob_price"
android:text=""
android:textColor="#cecece"
android:textSize="12dp" />
</RelativeLayout>
cartList.java
package com.epe.yehki.ui;
import java.util.ArrayList;
import java.util.HashMap;
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.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.epe.yehki.adapter.CartAdapter;
import com.epe.yehki.backend.BackendAPIService;
import com.epe.yehki.util.Const;
import com.epe.yehki.util.Pref;
import com.example.yehki.R;
public class CartListActivity extends Activity {
private ProgressDialog pDialog;
Intent in = null;
ListView lv;
JSONObject jsonObj;
ArrayList<HashMap<String, String>> cartList;
Bitmap bitmap;;
private CartAdapter cartContent;
JSONArray carts = null;
ImageView back;
TextView tv_place_order, tv_home;
String total, pid;
TextView tv_total;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_cart_list);
lv = (ListView) findViewById(R.id.cart_list);
back = (ImageView) findViewById(R.id.iv_bak);
tv_place_order = (TextView) findViewById(R.id.tv_place_order);
tv_home = (TextView) findViewById(R.id.tv_home);
tv_total = (TextView) findViewById(R.id.tv_total);
cartList = new ArrayList<HashMap<String, String>>();
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
// execute the cartList api()...........!!!!
new GetCartList().execute();
// listView ClickEvent
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
System.out.println("::::::::::::Long click:::::::::::::::::");
pid = cartList.get(position).get(Const.TAG_PRODUCT_ID);
showCustomeAlert(CartListActivity.this, "Are You Sure want to delete?", "Yehki", "No", "Yes", position, pid);
return false;
}
});
tv_home.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
in = new Intent(CartListActivity.this, HomeActivity.class);
startActivity(in);
}
});
tv_place_order.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
in = new Intent(CartListActivity.this, CartPlaceOrderActivity.class);
startActivity(in);
}
});
}
/*
* CART LIST PRODUCT LIST...............!!!!!!!!!
*/
private class GetCartList extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(CartListActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
String cartUrl = Const.API_CART_LIST + "?customer_id=" + Pref.getValue(CartListActivity.this, Const.PREF_CUSTOMER_ID, "");
BackendAPIService sh = new BackendAPIService();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(cartUrl, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
total = jsonObj.getString(Const.TAG_TOTAL);
// Getting JSON Array node
if (jsonObj.has(Const.TAG_PRO_LIST)) {
carts = jsonObj.getJSONArray(Const.TAG_PRO_LIST);
if (carts != null && carts.length() != 0) {
// looping through All Contacts
for (int i = 0; i < carts.length(); i++) {
JSONObject c = carts.getJSONObject(i);
String proId = c.getString(Const.TAG_PRODUCT_ID);
String proName = c.getString(Const.TAG_PRODUCT_NAME);
String wPrice = c.getString(Const.TAG_WHOLESALE_PRICE);
String rPrice = c.getString(Const.TAG_RETAIL_PRICE);
String qty = c.getString(Const.TAG_QUANTITY);
String subTotal = c.getString(Const.TAG_SUBTOTAL);
String proimg = Const.API_HOST + "/" + c.getString(Const.TAG_PRODUCT_IMG);
HashMap<String, String> cartProduct = new HashMap<String, String>();
cartProduct.put(Const.TAG_PRODUCT_ID, proId);
cartProduct.put(Const.TAG_PRODUCT_NAME, proName);
cartProduct.put(Const.TAG_PRODUCT_IMG, proimg);
cartProduct.put(Const.TAG_WHOLESALE_PRICE, wPrice);
cartProduct.put(Const.TAG_RETAIL_PRICE, rPrice);
cartProduct.put(Const.TAG_QUANTITY, qty);
cartProduct.put(Const.TAG_SUBTOTAL, subTotal);
cartProduct.put(Const.TAG_TOTAL, total);
cartList.add(cartProduct);
}
}
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("::::::::::::::::::got an error::::::::::::");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
cartContent = new CartAdapter(CartListActivity.this, cartList);
lv.setAdapter(cartContent);
StringBuilder b = new StringBuilder();
for (int i = 0; i > cartContent.getCount(); i++)
b.append(cartContent.getItem(i));
tv_total.setText("Total:" + total);
}
}
public void showCustomeAlert(final Context context, String message, String title, String leftButton, String rightButton, final int position, final String pid2) {
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.popup_alert_delete);
dialog.setCancelable(true);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
TextView txt_message = (TextView) dialog.findViewById(R.id.txtMessage);
final Button btn_left = (Button) dialog.findViewById(R.id.btnLeft);
final Button btn_right = (Button) dialog.findViewById(R.id.btnRigth);
TextView txtTitle = (TextView) dialog.findViewById(R.id.txtTitle);
txtTitle.setText(title);
txt_message.setText(message);
btn_left.setText(leftButton);
btn_right.setText(rightButton);
btn_left.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
btn_right.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String pid = cartList.get(position).get(Const.TAG_PRODUCT_ID);
cartList.clear();
new RemoveCart().execute(pid2);
cartContent.notifyDataSetChanged();
dialog.dismiss();
}
});
dialog.show();
}
/*
* Remove from cart List.........!!!
*/
private class RemoveCart extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(CartListActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(String... arg0) {
// Creating service handler class instance
String cartUrl = Const.API_REMOVE_CART_LIST + "?customer_id=" + Pref.getValue(CartListActivity.this, Const.PREF_CUSTOMER_ID, "") + "&product_id=" + arg0[0];
BackendAPIService sh = new BackendAPIService();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(cartUrl, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
total = jsonObj.getString(Const.TAG_TOTAL);
// Getting JSON Array node
if (jsonObj.has(Const.TAG_PRO_LIST)) {
carts = jsonObj.getJSONArray(Const.TAG_PRO_LIST);
if (carts != null && carts.length() != 0) {
// looping through All Contacts
for (int i = 0; i < carts.length(); i++) {
JSONObject c = carts.getJSONObject(i);
String proId = c.getString(Const.TAG_PRODUCT_ID);
String proName = c.getString(Const.TAG_PRODUCT_NAME);
String wPrice = c.getString(Const.TAG_WHOLESALE_PRICE);
String rPrice = c.getString(Const.TAG_RETAIL_PRICE);
String qty = c.getString(Const.TAG_QUANTITY);
String subTotal = c.getString(Const.TAG_SUBTOTAL);
String proimg = Const.API_HOST + "/" + c.getString(Const.TAG_PRODUCT_IMG);
HashMap<String, String> cartProduct = new HashMap<String, String>();
cartProduct.put(Const.TAG_PRODUCT_ID, proId);
cartProduct.put(Const.TAG_PRODUCT_NAME, proName);
cartProduct.put(Const.TAG_PRODUCT_IMG, proimg);
cartProduct.put(Const.TAG_WHOLESALE_PRICE, wPrice);
cartProduct.put(Const.TAG_RETAIL_PRICE, rPrice);
cartProduct.put(Const.TAG_QUANTITY, qty);
cartProduct.put(Const.TAG_SUBTOTAL, subTotal);
cartProduct.put(Const.TAG_TOTAL, total);
cartList.add(cartProduct);
}
}
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("::::::::::::::::::got an error::::::::::::");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
cartContent = new CartAdapter(CartListActivity.this, cartList);
lv.setAdapter(cartContent);
StringBuilder b = new StringBuilder();
for (int i = 0; i > cartContent.getCount(); i++)
b.append(cartContent.getItem(i));
tv_total.setText("Total:" + total);
}
}
}
cartAdapter.java
package com.epe.yehki.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.epe.yehki.backend.BackendAPIService;
import com.epe.yehki.ui.WholesaleProductDetailActivity;
import com.epe.yehki.util.Const;
import com.epe.yehki.util.Pref;
import com.example.yehki.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
public class CartAdapter extends BaseAdapter {
public ArrayList<HashMap<String, String>> cartArray;
private Context mContext;
private DisplayImageOptions options;
public static ImageLoader imageLoader;
String retailPrice;
String wholesalePrice;
String retailQty;
String wholesaleQty;
private ProgressDialog pDialog;
String status;
public CartAdapter(Context paramContext, ArrayList<HashMap<String, String>> cartList) {
this.mContext = paramContext;
this.cartArray = cartList;
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(paramContext));
options = new DisplayImageOptions.Builder().cacheOnDisc(true).showStubImage(R.drawable.logo).showImageOnFail(R.drawable.ic_launcher).build();
}
public int getCount() {
return this.cartArray.size();
}
public Object getItem(int paramInt) {
return Integer.valueOf(paramInt);
}
public long getItemId(int paramInt) {
return paramInt;
}
#SuppressWarnings("static-access")
public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) {
LayoutInflater localLayoutInflater = (LayoutInflater) this.mContext.getSystemService("layout_inflater");
Viewholder localViewholder = null;
if (paramView == null) {
paramView = localLayoutInflater.inflate(R.layout.raw_cart, paramViewGroup, false);
localViewholder = new Viewholder();
localViewholder.pid = ((TextView) paramView.findViewById(R.id.pro_id));
localViewholder.proImg = ((ImageView) paramView.findViewById(R.id.iv_product_img));
localViewholder.proName = ((TextView) paramView.findViewById(R.id.product_label));
localViewholder.price = ((TextView) paramView.findViewById(R.id.tv_wprice));
localViewholder.qty = ((EditText) paramView.findViewById(R.id.et_qty));
localViewholder.subTotal = ((TextView) paramView.findViewById(R.id.tv_rprice));
paramView.setTag(localViewholder);
} else {
localViewholder = new Viewholder();
localViewholder = (Viewholder) paramView.getTag();
}
System.out.println("::::::::::::::array indexes::::::::::::" + cartArray.get(paramInt));
retailQty = cartArray.get(paramInt).get(Const.TAG_MIN_ORDER_QTY_RETAIL);
retailPrice = cartArray.get(paramInt).get(Const.TAG_RETAIL_PRICE);
wholesaleQty = cartArray.get(paramInt).get(Const.TAG_MIN_ORDER_QTY_WHOLESALE);
wholesalePrice = cartArray.get(paramInt).get(Const.TAG_WHOLESALE_PRICE);
localViewholder.proName.setText(cartArray.get(paramInt).get(Const.TAG_PRODUCT_NAME));
localViewholder.pid.setText(cartArray.get(paramInt).get(Const.TAG_PRODUCT_ID));
localViewholder.pid.setVisibility(View.GONE);
localViewholder.qty.setText(cartArray.get(paramInt).get(Const.TAG_QUANTITY));
localViewholder.subTotal.setText(cartArray.get(paramInt).get(Const.TAG_SUBTOTAL));
/*
* for changing the price based on quantity....
*/
localViewholder.price.setText(cartArray.get(paramInt).get(Const.TAG_WHOLESALE_PRICE));
imageLoader.displayImage(cartArray.get(paramInt).get(Const.TAG_PRODUCT_IMG), localViewholder.proImg, options);
return paramView;
}
static class Viewholder {
ImageView proImg;
TextView proName;
TextView price;
TextView subTotal;
TextView pid;
EditText qty;
}
}
Use
myListView.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> listView, View view, int position, long id)
{
EditText yourEditText = (EditText) view.findViewById(R.id.youredittextid);
listView.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
yourEditText.requestFocus();
}
});
The problem is that the selection of the row takes the focus but in order to edit the EditText you need focus on it