How to implement CustomAdapter in ListView Acitivity - java
I want image before textview and want to customize TextView in each row but it is hard for me to implement it because there is already xml such layout file simple_list_item_1 made inbuilt.
Please help me how can i implement it.
Here is simple_list_item coding
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2006 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:gravity="center_vertical"
android:paddingStart="?android:attr/listPreferredItemPaddingStart"
android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
/>
Main Activity
public class MainActivity extends ListActivity {
private ListActivity activity;
final static String ScreenName = "google";
final static String LOG_TAG = "rnc";
ListView listview;
TextView text;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.twit_list);
listview = this.getListView();
activity = this;
downloadTweets();
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
String lst_txt = parent.getItemAtPosition(position).toString().trim();
// Launching new Activity on selecting single List Item
Intent i = new Intent(MainActivity.this, SingleListItem.class);
// sending data to new activity
i.putExtra("product",lst_txt );
startActivity(i);
}
});
}
// download twitter timeline after first checking to see if there is a network connection
public void downloadTweets() {
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new DownloadTwitterTask().execute(ScreenName);
} else {
Log.v(LOG_TAG, "No network connection available.");
}
}
// Uses an AsyncTask to download a Twitter user's timeline
private class DownloadTwitterTask extends AsyncTask<String, Void, String> {
final static String CONSUMER_KEY = "keyvaluexxxxx";
final static String CONSUMER_SECRET = "secretkeyxxxxxxx";
final static String TwitterTokenURL = "https://api.twitter.com/oauth2/token";
final static String TwitterStreamURL = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=";
private ProgressDialog progressDialog;
#Override
// can use UI thread here
protected void onPreExecute() {
//this.progressDialog = ProgressDialog.show(Boys.this, ""," Look whose back !! Ok Let me see what i have for you ");
try{
progressDialog = new ProgressDialog(MainActivity.this,AlertDialog.THEME_HOLO_DARK);
progressDialog.setIndeterminate(true);
progressDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.loader_2));
progressDialog.setMessage("Please Wait ! Unwrapping Something for You...");
progressDialog.show();
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
}
catch(Exception e)
{
this.progressDialog.dismiss();
Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_LONG).show();
}
}
#Override
protected String doInBackground(String... screenNames) {
String result = null;
if (screenNames.length > 0) {
result = getTwitterStream(screenNames[0]);
}
return result;
}
// onPostExecute convert the JSON results into a Twitter object (which is an Array list of tweets
#Override
protected void onPostExecute(String result) {
Twitter twits = jsonToTwitter(result);
// lets write the results to the console as well
for (Tweet tweet : twits) {
Log.i(LOG_TAG, tweet.getText());
}
// send the tweets to the adapter for rendering
ArrayAdapter<Tweet> adapter = new ArrayAdapter<Tweet>(activity, android.R.layout.simple_list_item_1, twits);
setListAdapter(adapter);
this.progressDialog.dismiss();
}
// converts a string of JSON data into a Twitter object
private Twitter jsonToTwitter(String result) {
Twitter twits = null;
if (result != null && result.length() > 0) {
try {
Gson gson = new Gson();
twits = gson.fromJson(result, Twitter.class);
} catch (IllegalStateException ex) {
// just eat the exception
}
}
return twits;
}
// convert a JSON authentication object into an Authenticated object
private Authenticated jsonToAuthenticated(String rawAuthorization) {
Authenticated auth = null;
if (rawAuthorization != null && rawAuthorization.length() > 0) {
try {
Gson gson = new Gson();
auth = gson.fromJson(rawAuthorization, Authenticated.class);
} catch (IllegalStateException ex) {
// just eat the exception
}
}
return auth;
}
private String getResponseBody(HttpRequestBase request) {
StringBuilder sb = new StringBuilder();
try {
DefaultHttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());
HttpResponse response = httpClient.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
String reason = response.getStatusLine().getReasonPhrase();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
String line = null;
while ((line = bReader.readLine()) != null) {
sb.append(line);
}
} else {
sb.append(reason);
}
} catch (UnsupportedEncodingException ex) {
} catch (ClientProtocolException ex1) {
} catch (IOException ex2) {
}
return sb.toString();
}
private String getTwitterStream(String screenName) {
String results = null;
// Step 1: Encode consumer key and secret
try {
// URL encode the consumer key and secret
String urlApiKey = URLEncoder.encode(CONSUMER_KEY, "UTF-8");
String urlApiSecret = URLEncoder.encode(CONSUMER_SECRET, "UTF-8");
// Concatenate the encoded consumer key, a colon character, and the
// encoded consumer secret
String combined = urlApiKey + ":" + urlApiSecret;
// Base64 encode the string
String base64Encoded = Base64.encodeToString(combined.getBytes(), Base64.NO_WRAP);
// Step 2: Obtain a bearer token
HttpPost httpPost = new HttpPost(TwitterTokenURL);
httpPost.setHeader("Authorization", "Basic " + base64Encoded);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
httpPost.setEntity(new StringEntity("grant_type=client_credentials"));
String rawAuthorization = getResponseBody(httpPost);
Authenticated auth = jsonToAuthenticated(rawAuthorization);
// Applications should verify that the value associated with the
// token_type key of the returned object is bearer
if (auth != null && auth.token_type.equals("bearer")) {
// Step 3: Authenticate API requests with bearer token
HttpGet httpGet = new HttpGet(TwitterStreamURL + screenName);
// construct a normal HTTPS request and include an Authorization
// header with the value of Bearer <>
httpGet.setHeader("Authorization", "Bearer " + auth.access_token);
httpGet.setHeader("Content-Type", "application/json");
// update the results with the body of the response
results = getResponseBody(httpGet);
}
} catch (UnsupportedEncodingException ex) {
} catch (IllegalStateException ex1) {
}
return results;
}
}
}
Here twit_list.xml attached with MainActivity.java
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/bis"
>
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
Create a custom_item inside layout folder
<LinearLayout 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:orientation="horizontal" >
<ImageView
android:id="#+id/listItemImgView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/done"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/listItemTxtView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
Create a custom adapter like this
public class CustomAdapter extends ArrayAdapter<Tweet> {
private Context mContext;
private int layoutId;
private ArrayList<Tweet> dataList;
public CustomAdapter(Context context, int resourceId,
ArrayList<Tweet> objects) {
super(context, resourceId, objects);
// TODO Auto-generated constructor stub
mContext = context;
layoutId = resourceId;
dataList = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder viewHolder;
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(layoutId, null);
viewHolder = new ViewHolder();
viewHolder.listItemTxtView = (TextView) convertView.findViewById(R.id.listItemTxtView);
viewHolder.listItemImgView = (ImageView) convertView.findViewById(R.id.listItemImgView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.listItemTxtView.setText(dataList.get(position).toString());
//place picasso jar into libs folder of your project and use it for download and set images like this
Picasso.with(context).load("url of image you want to load").into(viewHolder.listItemImgView);
return convertView;
}
private class ViewHolder {
TextView listItemTxtView;
ImageView listItemImgView;
}
}
download picasso jar from here
instead of this
ArrayAdapter<Tweet> adapter = new ArrayAdapter<Tweet>(activity, android.R.layout.simple_list_item_1, twits);
setListAdapter(adapter);
Use this
CustomAdapter adapter = new CustomAdapter(MainActivity.this, R.layout.custom_item, twits);
setListAdapter(adapter);
Related
How to fix an empty fragment?
I am new to Android development, trying to create my own app. It should display a particular YouTube Channel by using the YouTube Data API. I have started with the standard bottom navigation template in Android Studio and used the following project on Github for some start-up help. https://github.com/stressGC/Remake-YouTube-Android I had to change a few things like the deprecated http call inside the code to keep it running with the new Android APKs. Everything seems fine from my point of view: I can see that the API content looks good and that each title / description / publishdate is placed in the according variables. There is also no error message in the log. When I start the emulator, the app is running fine. But as soon as I switch to the "Dashboard" fragment (where the code is placed), it is empty. DashboardFragment.java public class DashboardFragment extends Fragment { private static String API_KEY = "hidden"; //normaler API key ohne limits, kein oauth private static String CHANNEL_ID = "hidden"; private static String CHANNEL_GET_URL = "https://www.googleapis.com/youtube/v3/search?part=snippet&order=date&channelId="+CHANNEL_ID+"&maxResults=20&key="+API_KEY+""; private RecyclerView mList_videos = null; private VideoPostAdapter adapter = null; private ArrayList<YouTubeDataModel> mListData = new ArrayList<>(); public DashboardFragment () { } #Override public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_dashboard, container, false); mList_videos = (RecyclerView) view.findViewById(R.id.mList_videos); initList(mListData); new RequestYouTubeAPI().execute(); return view; } private void initList(ArrayList<YouTubeDataModel> mListData) { mList_videos.setLayoutManager(new LinearLayoutManager(getActivity())); adapter = new VideoPostAdapter(getActivity(), mListData); mList_videos.setAdapter(adapter); } // create asynctask to get data from youtube private class RequestYouTubeAPI extends AsyncTask<Void, String, String>{ #Override protected void onPreExecute() { super.onPreExecute(); } #Override protected String doInBackground(Void... params) { URL url = null; String json = null; StringBuffer sb = new StringBuffer(); try { url = new URL(CHANNEL_GET_URL); } catch (MalformedURLException e) { e.printStackTrace(); } try { //HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); HttpURLConnection urlConnection = NetCipher.getHttpsURLConnection(url); InputStream in = new BufferedInputStream(urlConnection.getInputStream()); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String inputLine = ""; while ((inputLine = br.readLine()) != null) { sb.append(inputLine); } json = sb.toString(); return json; } catch (IOException e) { e.printStackTrace(); return null; } } #Override protected void onPostExecute(String response) { super.onPostExecute(response); if(response != null){ try { JSONObject jsonObject = new JSONObject(response); Log.e("response", jsonObject.toString()); mListData = parseVideoListFromResponse(jsonObject); initList(mListData); //adapter.notifyDataSetChanged(); } catch (JSONException e) { e.printStackTrace(); } } } } public ArrayList<YouTubeDataModel> parseVideoListFromResponse(JSONObject jsonObject) { ArrayList<YouTubeDataModel> mList = new ArrayList<>(); if (jsonObject.has("items")) { try { JSONArray jsonArray = jsonObject.getJSONArray("items"); for (int i = 0; i < jsonArray.length(); i++) { JSONObject json = jsonArray.getJSONObject(i); if (json.has("id")) { JSONObject jsonID = json.getJSONObject("id"); String video_id = ""; if (jsonID.has("videoId")) { video_id = jsonID.getString("videoId"); } if (jsonID.has("kind")) { if (jsonID.getString("kind").equals("youtube#video")) { YouTubeDataModel youtubeObject = new YouTubeDataModel(); JSONObject jsonSnippet = json.getJSONObject("snippet"); String title = jsonSnippet.getString("title"); String description = jsonSnippet.getString("description"); String publishedAt = jsonSnippet.getString("publishedAt"); String thumbnail = jsonSnippet.getJSONObject("thumbnails").getJSONObject("high").getString("url"); youtubeObject.setTitle(title); youtubeObject.setDescription(description); youtubeObject.setPublishedAt(publishedAt); youtubeObject.setThumbnail(thumbnail); youtubeObject.setVideo_id(video_id); mList.add(youtubeObject); } } } } } catch (JSONException e) { e.printStackTrace(); } } return mList; } } VideoPostAdapter.java public class VideoPostAdapter extends RecyclerView.Adapter<VideoPostAdapter.YouTubePostHolder> { private ArrayList<YouTubeDataModel> dataSet; private Context mContext = null; public VideoPostAdapter(Context mContext, ArrayList<YouTubeDataModel> dataSet) { this.dataSet = dataSet; this.mContext = mContext; } #NonNull #Override public YouTubePostHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.youtube_post_layout,parent,false); YouTubePostHolder postHolder = new YouTubePostHolder(view); return postHolder; } #Override public void onBindViewHolder(#NonNull YouTubePostHolder holder, int position) { // set the views here TextView textViewTitle = holder.textViewTitle; TextView textViewDes = holder.textViewDes; TextView textViewDate = holder.textViewDate; ImageView ImageThumb = holder.ImageThumb; YouTubeDataModel object = dataSet.get(position); textViewTitle.setText(object.getTitle()); textViewDes.setText(object.getDescription()); textViewDate.setText(object.getPublishedAt()); // image will be downloaded from url } #Override public int getItemCount() { return dataSet.size(); } public static class YouTubePostHolder extends RecyclerView.ViewHolder{ TextView textViewTitle; TextView textViewDes; TextView textViewDate; ImageView ImageThumb; public YouTubePostHolder(#NonNull View itemView) { super(itemView); this.textViewTitle = (TextView) itemView.findViewById(R.id.textViewTitle); this.textViewDes = (TextView) itemView.findViewById(R.id.textViewDes); this.textViewDate = (TextView) itemView.findViewById(R.id.textViewDate); this.ImageThumb = (ImageView) itemView.findViewById(R.id.ImageThumb); } } } YouTubeDataModel.java public class YouTubeDataModel { private String title = ""; private String description = ""; private String publishedAt = ""; private String thumbnail = ""; public String getVideo_id() { return video_id; } public void setVideo_id(String video_id) { this.video_id = video_id; } private String video_id = ""; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getPublishedAt() { return publishedAt; } public void setPublishedAt(String publishedAt) { this.publishedAt = publishedAt; } public String getThumbnail() { return thumbnail; } public void setThumbnail(String thumbnail) { this.thumbnail = thumbnail; } } youtube_post_layout.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content"> <RelativeLayout android:layout_width="match_parent" android:layout_height="200dp"> <ImageView android:id="#+id/ImageThumb" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#color/colorPrimary"/> <TextView android:id="#+id/textViewDate" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="published at" android:singleLine="true" android:layout_alignParentRight="true" android:layout_margin="5dp" android:textColor="#android:color/white" android:textSize="12dp"/> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_margin="10dp" android:orientation="vertical"> <TextView android:id="#+id/textViewTitle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="video Title" android:singleLine="true" android:textColor="#android:color/white" android:textSize="22dp"/> <TextView android:id="#+id/textViewDes" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="video description" android:singleLine="true" android:textColor="#android:color/white" android:textSize="12dp"/> </LinearLayout> </RelativeLayout> </LinearLayout> fragment_dashboard.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:layout_height="match_parent"> <androidx.recyclerview.widget.RecyclerView android:id="#+id/mList_videos" android:layout_width="match_parent" android:layout_height="match_parent" /> </androidx.constraintlayout.widget.ConstraintLayout> Unfortunately I have no idea why the fragment is still empty. And without any error in Android Studio log I really hope you can help me :/
Inside your RequestYouTubeAPI ASyncTask you have this error code: } catch (IOException e) { e.printStackTrace(); return null; } Then in onPostExecute you have the following: #Override protected void onPostExecute(String response) { super.onPostExecute(response); if(response != null){ try { JSONObject jsonObject = new JSONObject(response); Log.e("response", jsonObject.toString()); mListData = parseVideoListFromResponse(jsonObject); initList(mListData); //adapter.notifyDataSetChanged(); } catch (JSONException e) { e.printStackTrace(); } } } Therefore if you get an error, you return null and if onPostExecute is given a null response it does nothing. So this one place you could have an error and therefore a blank fragment. Before you fix this, you can prove this is happening like so: #Override protected void onPostExecute(String response) { super.onPostExecute(response); if(response == null){ Log.e("TUT", "We did not get a response, not updating the UI."); } else { try { JSONObject jsonObject = new JSONObject(response); Log.e("response", jsonObject.toString()); mListData = parseVideoListFromResponse(jsonObject); initList(mListData); //adapter.notifyDataSetChanged(); } catch (JSONException e) { e.printStackTrace(); } } } You can fix this two ways: in doInBackground change the catch to this: } catch (IOException e) { Log.e("TUT", "error", e); // Change this JSON to match what the parse expects, so you can show an error on the UI return "{\"yourJson\":\"error!\"}"; } or onPostExecute: if(response == null){ List errorList = new ArrayList(); // Change this data model to show an error case to the UI errorList.add(new YouTubeDataModel("Error"); mListData = errorList; initList(mListData); } else { try { JSONObject jsonObject = new JSONObject(response); Log.e("response", jsonObject.toString()); mListData = parseVideoListFromResponse(jsonObject); initList(mListData); //adapter.notifyDataSetChanged(); } catch (JSONException e) { e.printStackTrace(); } } Hope that helps, there may be other errors in the code but this is one case that can happen if there is a problem with the API, the Json, the authorization, the internet etc.
how do i displaying JSON results in a ListView
i have the following Code and lists displaying wrong results on my Listview. public class ZonesActivity extends AppCompatActivity { ListView mListView; #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_zones); String myJSONString = null; String myJSONObject = null; ArrayList<Zones> allZones = new ArrayList<Zones>(); try { InputStream inputStream = getAssets().open("zonesjson.json"); int sizeOfJSONFile = inputStream.available(); byte[] bytes = new byte[sizeOfJSONFile]; inputStream.read(bytes); //close the input stream inputStream.close(); myJSONString = new String(bytes, "UTF-8"); myJSONObject = new JSONObject(myJSONString).toString(); } catch (IOException | JSONException e) { e.printStackTrace(); } try { JSONObject jsonObjMain = new JSONObject(myJSONObject); // Creating JSONArray from JSONObject JSONArray jsonArray = jsonObjMain.getJSONArray("zones"); for (int i = 0; i < jsonArray.length(); i++) { // Creating JSONObject from JSONArray JSONObject jsonObj = jsonArray.getJSONObject(i); // Getting data from individual JSONObject String zname = jsonObj.getString("zname"); String location = jsonObj.getString("location"); String pastname = jsonObj.getString("pastname"); int starttime = jsonObj.getInt("starttime"); int endtime = jsonObj.getInt("endtime"); String contactdetails = jsonObj.getString("contactdetails"); String address = jsonObj.getString("address"); Zones zonesList = new Zones(); zonesList.setZoneName(zname); zonesList.setZoneLocation(location); zonesList.setZonePastor(pastname); zonesList.setZoneStartTime(starttime); zonesList.setZoneEndTime(endtime); zonesList.setZoneContactNumber(contactdetails); zonesList.setZoneAddress(address); allZones.add(zonesList); } mListView = (ListView)findViewById(R.id.zoneListView1); ArrayAdapter arrayAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, allZones); mListView.setAdapter(arrayAdapter); } catch (JSONException e) { e.printStackTrace(); } } } its Displaying the following results on my emulator: please assist where i am getting is wrong
You should create a custom array adapter. The default one doesn't know how to display an entity "Zones", so it displays zones.toString() for each item. Hope that this example to help you: public class ZonesAdapter extends ArrayAdapter<Zones> { public ZonesAdapter(Context context, int resource, List<Zones> objects) { super(context, resource, objects); } #Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.zones_item_layout, parent, false); } Zones item = getItem(position); TextView title = (TextView) convertView.findViewById(R.id.title); title.setText(item.getZoneName()); // ... // Set other fields // ... return convertView; } } Then ZonesAdapter arrayAdapter = new ZonesAdapter(this, R.layout.zones_item_layout, allZones); mListView.setAdapter(arrayAdapter); zones_item_layout.xml: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:id="#+id/title" android:layout_width="match_parent" android:layout_height="wrap_content" /> // Add other views </LinearLayout>
ListView item onClick can't show wanted result
This is the listview. It only shows 3 type of info(i.e. job post name, location, salary) in each item : Job post name 1 Location 1 Salary 1 For example, the above 3 info is item 1 in the listview. If I click item 1, it is supposed to show the above 3 info plus 3 more info , i.e. Job Responsibility, Company , Contact : Job post name 1 Location 1 Salary 1 Job Responsibility 1 Company 1 Contact 1 However, it fails. It only shows the first 3 info only, without Job Responsibility, Company and Contact. Could anyone help ? Thank you MainActivity.java public class MainActivity extends ListActivity { private ProgressDialog pDialog; // URL to get contacts JSON private static String url = "http://192.168.0.102/get_json_select_all.php"; // JSON Node names private static final String TAG_INFO = "info"; private static final String TAG_POSTNAME = "PostName"; private static final String TAG_LOCATION = "Location"; private static final String TAG_SALARY = "Salary"; private static final String TAG_RESPONSIBILITY = "Responsibility"; private static final String TAG_COMPANY = "Company"; private static final String TAG_CONTACT = "Contact"; // contacts JSONArray JSONArray infos = null; // Hashmap for ListView ArrayList<HashMap<String, String>> infoList; #Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); infoList = new ArrayList<HashMap<String, String>>(); ListView lv = getListView(); // Listview on item click listener lv.setOnItemClickListener(new OnItemClickListener() { #Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // getting values from selected ListItem String name = ((TextView) view.findViewById(R.id.PostName)) .getText().toString(); String cost = ((TextView) view.findViewById(R.id.Location)) .getText().toString(); String description = ((TextView) view.findViewById(R.id.Salary)) .getText().toString(); // Starting single contact activity Intent in = new Intent(getApplicationContext(), SingleContactActivity.class); in.putExtra(TAG_POSTNAME, name); in.putExtra(TAG_LOCATION, cost); in.putExtra(TAG_SALARY, description); startActivity(in); } }); // Calling async task to get json new GetContacts().execute(); } /** * Async task class to get json by making HTTP call * */ private class GetContacts extends AsyncTask<Void, Void, Void> { #Override protected void onPreExecute() { super.onPreExecute(); // Showing progress dialog pDialog = new ProgressDialog(MainActivity.this); pDialog.setMessage("Please wait..."); pDialog.setCancelable(false); pDialog.show(); } #Override protected Void doInBackground(Void... arg0) { // Creating service handler class instance ServiceHandler sh = new ServiceHandler(); // Making a request to url and getting response String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET); Log.d("Response: ", "> " + jsonStr); if (jsonStr != null) { try { JSONObject jsonObj = new JSONObject(jsonStr); // Getting JSON Array node infos = jsonObj.getJSONArray(TAG_INFO); // looping through All Contacts for (int i = 0; i < infos.length(); i++) { JSONObject c = infos.getJSONObject(i); String id = c.getString(TAG_POSTNAME); String name = c.getString(TAG_LOCATION); String email = c.getString(TAG_SALARY); String address = c.getString(TAG_RESPONSIBILITY); String gender = c.getString(TAG_COMPANY); String mobile = c.getString(TAG_CONTACT); // tmp hashmap for single contact HashMap<String, String> info = new HashMap<String, String>(); // adding each child node to HashMap key => value info.put(TAG_POSTNAME, id); info.put(TAG_LOCATION, name); info.put(TAG_SALARY, email); info.put(TAG_RESPONSIBILITY, address); info.put(TAG_COMPANY, gender); info.put(TAG_CONTACT, mobile); // adding contact to contact list infoList.add(info); } } catch (JSONException e) { e.printStackTrace(); } } else { Log.e("ServiceHandler", "Couldn't get any data from the url"); } return null; } #Override protected void onPostExecute(Void result) { super.onPostExecute(result); // Dismiss the progress dialog if (pDialog.isShowing()) pDialog.dismiss(); /** * Updating parsed JSON data into ListView * */ ListAdapter adapter = new SimpleAdapter( MainActivity.this, infoList, R.layout.list_item, new String[] { TAG_POSTNAME, TAG_LOCATION, TAG_SALARY }, new int[] { R.id.PostName, R.id.Location, R.id.Salary }); setListAdapter(adapter); } } } SingleContactActivity.java public class SingleContactActivity extends Activity { // JSON node keys private static final String TAG_POSTNAME = "PostName"; private static final String TAG_LOCATION = "Location"; private static final String TAG_SALARY = "Salary"; private static final String TAG_RESPONSIBILITY = "Responsibility"; private static final String TAG_COMPANY = "Company"; private static final String TAG_CONTACT = "Contact"; #Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_single_contact); // getting intent data Intent in = getIntent(); // Get JSON values from previous intent String PostName = in.getStringExtra(TAG_POSTNAME); String Location = in.getStringExtra(TAG_LOCATION); String Salary = in.getStringExtra(TAG_SALARY); String Responsibility = in.getStringExtra(TAG_RESPONSIBILITY); String Company = in.getStringExtra(TAG_COMPANY); String Contact = in.getStringExtra(TAG_CONTACT); // Displaying all values on the screen TextView lblPostName = (TextView) findViewById(R.id.PostName_label); TextView lblLocation = (TextView) findViewById(R.id.Location_label); TextView lblSalary = (TextView) findViewById(R.id.Salary_label); TextView lblResponsibility = (TextView) findViewById(R.id.Responsibility_label); TextView lblCompany = (TextView) findViewById(R.id.Company_label); TextView lblContact = (TextView) findViewById(R.id.Contact_label); lblPostName.setText(PostName); lblLocation.setText(Location); lblSalary.setText(Salary); lblResponsibility.setText(Responsibility); lblCompany.setText(Company); lblContact.setText(Contact); } } ServiceHandler.java public class ServiceHandler { static String response = null; public final static int GET = 1; public final static int POST = 2; public ServiceHandler() { } public String makeServiceCall(String url, int method) { return this.makeServiceCall(url, method, null); } public String makeServiceCall(String url, int method, List<NameValuePair> params) { try { // http client DefaultHttpClient httpClient = new DefaultHttpClient(); HttpEntity httpEntity = null; HttpResponse httpResponse = null; // Checking http request method type if (method == POST) { HttpPost httpPost = new HttpPost(url); // adding post params if (params != null) { httpPost.setEntity(new UrlEncodedFormEntity(params)); } httpResponse = httpClient.execute(httpPost); } else if (method == GET) { // appending params to url if (params != null) { String paramString = URLEncodedUtils .format(params, "utf-8"); url += "?" + paramString; } HttpGet httpGet = new HttpGet(url); httpResponse = httpClient.execute(httpGet); } httpEntity = httpResponse.getEntity(); response = EntityUtils.toString(httpEntity); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return response; } } acticity_main.xml <ListView android:id="#android:id/list" android:layout_width="fill_parent" android:layout_height="wrap_content"/> list_item.xml <TextView android:id="#+id/PostName" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingBottom="2dip" android:paddingTop="6dip" android:textColor="#43bd00" android:textSize="16sp" android:textStyle="bold" /> <TextView android:id="#+id/Location" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingBottom="2dip" android:textColor="#acacac" /> <TextView android:id="#+id/Salary" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="left" android:text="Salary: " android:textColor="#5d5d5d" android:textStyle="bold" /> activity_single_contact.xml <TextView android:id="#+id/PostName_label" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="25dip" android:textStyle="bold" android:paddingTop="10dip" android:paddingBottom="10dip" android:textColor="#43bd00"/> <TextView android:id="#+id/Location_label" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textColor="#acacac"/> <TextView android:id="#+id/Salary_label" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textStyle="bold"/> <TextView android:id="#+id/Responsibility_label" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textColor="#ff1e76ac"/> <TextView android:id="#+id/Company_label" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textColor="#ff1e76ac"/> <TextView android:id="#+id/Contact_label" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textColor="#ff1e76ac"/>
edit this part of code final listView lv=getListView(); lv.setOnItemClickListener(new OnItemClickListener() { #Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // getting values from selected ListItem String name = ((TextView) view.findViewById(R.id.PostName)) .getText().toString(); String cost = ((TextView) view.findViewById(R.id.Location)) .getText().toString(); String description = ((TextView) view.findViewById(R.id.Salary)) .getText().toString(); HashMap<String, String> info = new HashMap<String, String>(); info=(HashMap<String, String>)lv.getAdapter().getItem(position); // Starting single contact activity Intent in = new Intent(getApplicationContext(), SingleContactActivity.class); in.putExtra(TAG_POSTNAME, name); in.putExtra(TAG_LOCATION, cost); in.putExtra(TAG_SALARY, description); in.putExtra(RESPONSIBILITY, info.get(TAG_RESPONSIBILITY)); in.putExtra(TAG_COMPANY, info.get(TAG_COMPANY)); in.putExtra(TAG_CONTACT, info.get(TAG_CONTACT)); startActivity(in);
json array shows in logacat with no errors but does not show in android view
A large part of my app is grabbing data from a website. The data shows in my logcat, green with no errors but will not display in my android view. Ive tried and searched for a week or and have had no luck. here is my class. public class Json extends ListActivity { ArrayList<HashMap<String, String>> jsonParser = new ArrayList<HashMap<String, String>>(); ListView lv ; private static final String jsonFilePath = "http://xda.olinksoftware.com/leaderboard/all"; #Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.json); new ProgressTask(Json.this).execute(); } private class ProgressTask extends AsyncTask<String, Void, Boolean> { private ProgressDialog dialog; public ProgressTask(Json json) { Log.i("1", "Called"); context = json; dialog = new ProgressDialog(context); } private Context context; protected void onPreExecute() { this.dialog.setMessage("Progress start"); this.dialog.show(); } #Override protected void onPostExecute(final Boolean success) { if (dialog.isShowing()) { dialog.dismiss(); } ListAdapter adapter = new SimpleAdapter(context, jsonParser, R.layout.listitem, new String[] { TAG_NAME, TAG_SCORE, }, new int[] { R.id.score, R.id.name, }); setListAdapter(adapter); // selecting single ListView item lv = getListView(); } #Override protected Boolean doInBackground(final String... args) { new JSONParser(); try { BufferedReader reader = null; String jsonString = ""; StringBuffer buffer = new StringBuffer(); try{ URL url = new URL(jsonFilePath); reader = new BufferedReader(new InputStreamReader(url.openStream())); int read; char[] chars = new char[1024]; while ((read = reader.read(chars)) != -1) buffer.append(chars, 0, read); }finally { if (reader != null) reader.close(); } jsonString = buffer.toString(); try{ JSONParser jsonParser = new JSONParser(); JSONArray leaderboard = (JSONArray)jsonParser.parse(jsonString); for(int i = 0;i<leaderboard.size();i++){ JSONObject user = (JSONObject)leaderboard.get(i); System.out.println((i+1) + ". " + user.get("forumName") + " (" + user.get("score") + ")"); } }catch(ParseException pe){ System.out.println("position: " + pe.getPosition()); System.out.println(pe); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }} } and here are my xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <!-- Main ListView Always give id value as list(#android:id/list) --> <ListView android:id="#android:id/list" android:layout_width="fill_parent" android:layout_height="wrap_content"/> </LinearLayout> <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical"> <!-- Product id (pid) - will be HIDDEN - used to pass to other activity --> <TextView android:id="#+id/name" android:layout_width="fill_parent" android:layout_height="wrap_content" android:visibility="gone" /> <!-- Name Label --> <TextView android:id="#+id/score" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingTop="6dp" android:paddingLeft="6dp" android:textSize="17sp" android:textStyle="bold"/> </LinearLayout> any help is greatly appreciated. I know I am doing something wrong with my listview as it also works as a straight java application run in eclipse. here is the data i am grabbing, i am only taking two values at this time. "forumUser" and "score" [{"userId":"3579348","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=3579348","forumName":"newtoroot","totalPosts":"5074","postsPerDay":"5.14","totalThanks":"18302","joinDate":"2011-01-29","yearsJoined":"2","referrals":"4","friendCount":"38","recognizedDeveloper":"1","recognizedContributor":"0","recognizedThemer":"0","moderator":"0","recognizedEliteDeveloper":"0","romCount":"48","kernelCount":"0","tutorialCount":"0","modCount":"1","themeCount":"0","score":"302","userName":"","password":""},{"userId":"1596076","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=1596076","forumName":"il Duce","totalPosts":"16335","postsPerDay":"9.75","totalThanks":"15799","joinDate":"2009-02-25","yearsJoined":"4","referrals":"2","friendCount":"83","recognizedDeveloper":"1","recognizedContributor":"0","recognizedThemer":"0","moderator":"1","recognizedEliteDeveloper":"0","romCount":"1","kernelCount":"1","tutorialCount":"0","modCount":"0","themeCount":"0","score":"132","userName":"","password":""},{"userId":"2930301","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=2930301","forumName":"fernando sor","totalPosts":"8967","postsPerDay":"7.93","totalThanks":"4549","joinDate":"2010-09-07","yearsJoined":"3","referrals":"2","friendCount":"29","recognizedDeveloper":"0","recognizedContributor":"0","recognizedThemer":"1","moderator":"0","recognizedEliteDeveloper":"0","romCount":"1","kernelCount":"0","tutorialCount":"5","modCount":"2","themeCount":"15","score":"120","userName":"fernando sor","password":""},{"userId":"3220669","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=3220669","forumName":"1975jamie","totalPosts":"582","postsPerDay":"0.56","totalThanks":"127","joinDate":"2010-11-23","yearsJoined":"2","referrals":"0","friendCount":"0","recognizedDeveloper":"1","recognizedContributor":"0","recognizedThemer":"0","moderator":"0","recognizedEliteDeveloper":"0","romCount":"4","kernelCount":"0","tutorialCount":"0","modCount":"0","themeCount":"0","score":"46","userName":"1975jamie","password":""},{"userId":"2552854","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=2552854","forumName":"jeffsanace","totalPosts":"2797","postsPerDay":"2.25","totalThanks":"2836","joinDate":"2010-05-05","yearsJoined":"3","referrals":"0","friendCount":"12","recognizedDeveloper":"0","recognizedContributor":"1","recognizedThemer":"0","moderator":"0","recognizedEliteDeveloper":"0","romCount":"0","kernelCount":"0","tutorialCount":"0","modCount":"0","themeCount":"0","score":"37","userName":"","password":""},{"userId":"2067958","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=2067958","forumName":"eg1122","totalPosts":"1200","postsPerDay":"0.82","totalThanks":"1695","joinDate":"2009-10-05","yearsJoined":"3","referrals":"0","friendCount":"6","recognizedDeveloper":"0","recognizedContributor":"0","recognizedThemer":"0","moderator":"0","recognizedEliteDeveloper":"0","romCount":"0","kernelCount":"0","tutorialCount":"0","modCount":"2","themeCount":"0","score":"20","userName":"","password":""},{"userId":"3042344","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=3042344","forumName":"dfuse06","totalPosts":"3331","postsPerDay":"3.08","totalThanks":"2270","joinDate":"2010-10-11","yearsJoined":"2","referrals":"1","friendCount":"29","recognizedDeveloper":"0","recognizedContributor":"0","recognizedThemer":"0","moderator":"0","recognizedEliteDeveloper":"0","romCount":"0","kernelCount":"0","tutorialCount":"0","modCount":"1","themeCount":"0","score":"17","userName":"","password":""},{"userId":"1070340","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=1070340","forumName":"chrisloveskaos","totalPosts":"215","postsPerDay":"0.11","totalThanks":"8","joinDate":"2008-07-08","yearsJoined":"5","referrals":"0","friendCount":"7","recognizedDeveloper":"0","recognizedContributor":"0","recognizedThemer":"0","moderator":"0","recognizedEliteDeveloper":"0","romCount":"1","kernelCount":"0","tutorialCount":"0","modCount":"0","themeCount":"0","score":"14","userName":"","password":""},{"userId":"2688514","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=2688514","forumName":"GooTz66","totalPosts":"999","postsPerDay":"0.84","totalThanks":"70","joinDate":"2010-06-25","yearsJoined":"3","referrals":"0","friendCount":"7","recognizedDeveloper":"0","recognizedContributor":"0","recognizedThemer":"0","moderator":"0","recognizedEliteDeveloper":"0","romCount":"0","kernelCount":"0","tutorialCount":"0","modCount":"0","themeCount":"0","score":"7","userName":"","password":""},{"userId":"2141845","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=2141845","forumName":"Kush.Kush\u00c2\u0099","totalPosts":"86","postsPerDay":"0.06","totalThanks":"0","joinDate":"2009-11-09","yearsJoined":"3","referrals":"0","friendCount":"16","recognizedDeveloper":"0","recognizedContributor":"0","recognizedThemer":"0","moderator":"0","recognizedEliteDeveloper":"0","romCount":"0","kernelCount":"0","tutorialCount":"0","modCount":"0","themeCount":"0","score":"6","userName":"","password":""}]
Why is this line setListAdapter(adapter); Before this // selecting single ListView item lv = getListView(); Also, the LogCat you posted is showing the results using the "info" filter only. Try looking at the verbose view to make sure no exceptions that you're missing.
what i did to solve this was pretty much start over. i added a JSONParser class public class JSONParser { static InputStream is = null; static JSONArray jarray = null; static String json = ""; // constructor public JSONParser() { } public JSONArray getJSONFromUrl(String url) { StringBuilder builder = new StringBuilder(); HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); try { HttpResponse response = client.execute(httpGet); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; while ((line = reader.readLine()) != null) { builder.append(line); } } else { Log.e("==>", "Failed to download file"); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // try parse the string to a JSON object try { jarray = new JSONArray( builder.toString()); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // return JSON String return jarray; and a JsonActivity public class MainActivity extends ListActivity { private static String url = "website"; private static final String TAG_VTYPE = "forumName"; private static final String TAG_VCOLOR = "score"; private static final String TAG_THANKS = "totalThanks"; private static final String TAG_POSTS = "totalPosts"; private static final String TAG_JOIN_DATE = "joinDate"; private static final String TAG_ROM_COUNT = "romCount"; private static final String TAG_THEME_COUNT = "themeCount"; private static final String TAG_MOD_COUNT = "modCount"; private static final String TAG_KERNEL_COUNT = "kernelCount"; private static final String TAG_TUTORIAL_COUNT = "tutorialCount"; private static final String TAG_DEV = "recognizedDeveloper"; private static final String TAG_THEMER = "recognizedThemer"; private static final String TAG_MODERATOR = "moderator"; private static final String TAG_RDEV = "recognizedEliteDeveloper"; private static final String TAG_RCOD = "recognizedContributor"; ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>(); private View header; ListView lv ; LayoutInflater Inflater; #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_view); Inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); new ProgressTask(MainActivity.this).execute(); } private class ProgressTask extends AsyncTask<String, Void, Boolean> { private ProgressDialog dialog; private ListActivity activity; // private List<Message> messages; public ProgressTask(ListActivity activity) { this.activity = activity; context = activity; dialog = new ProgressDialog(context); } /** progress dialog to show user that the backup is processing. */ /** application context. */ private Context context; protected void onPreExecute() { this.dialog.setMessage("Progress start"); this.dialog.show(); } #Override protected void onPostExecute(final Boolean success) { if (dialog.isShowing()) { dialog.dismiss(); } View header = Inflater.inflate(R.layout.header_view_name, null); ListAdapter adapter = new SimpleAdapter(context, jsonlist, R.layout.list_item, new String[] { TAG_VTYPE, TAG_VCOLOR, TAG_THANKS, TAG_POSTS, TAG_JOIN_DATE, TAG_ROM_COUNT, TAG_THEME_COUNT, TAG_MOD_COUNT, TAG_KERNEL_COUNT, TAG_DEV, TAG_TUTORIAL_COUNT, TAG_THEMER, TAG_MODERATOR, TAG_RDEV, TAG_RCOD, }, new int[] { R.id.vehicleType, R.id.vehicleColor, R.id.totalThanks, R.id.totalPosts, R.id.joinDate, R.id.romCount, R.id.themeCount, R.id.kernelCount, R.id.modCount, R.id.tutorialCount, R.id.moderator, R.id.rThemer, R.id.rDev, R.id.rCon, R.id.rEliteDev, }); lv = getListView(); lv.addHeaderView(header); setListAdapter(adapter); // selecting single ListView item // Launching new screen on Selecting Single ListItem lv.setOnItemClickListener(new OnItemClickListener() { ; #Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // getting values from selected ListItem String forumName = ((TextView) view.findViewById(R.id.vehicleType)).getText().toString(); String score = ((TextView) view.findViewById(R.id.vehicleColor)).getText().toString(); String totalThanks = ((TextView) view.findViewById(R.id.totalThanks)).getText().toString(); String totalPosts = ((TextView) view.findViewById(R.id.totalPosts)).getText().toString(); String joinDate = ((TextView) view.findViewById(R.id.joinDate)).getText().toString(); String romCount = ((TextView) view.findViewById(R.id.romCount)).getText().toString(); String themeCount = ((TextView) view.findViewById(R.id.themeCount)).getText().toString(); String kernelCount = ((TextView) view.findViewById(R.id.kernelCount)).getText().toString(); String modCount = ((TextView) view.findViewById(R.id.modCount)).getText().toString(); String tutorialCount = ((TextView) view.findViewById(R.id.tutorialCount)).getText().toString(); String moderator = ((TextView) view.findViewById(R.id.moderator)).getText().toString(); String recognizedThemer = ((TextView) view.findViewById(R.id.rThemer)).getText().toString(); String recognizedDeveloper = ((TextView) view.findViewById(R.id.rDev)).getText().toString(); String recognizedContributor = ((TextView) view.findViewById(R.id.rCon)).getText().toString(); String recognizedEliteDeveloper = ((TextView) view.findViewById(R.id.rEliteDev)).getText().toString(); // Starting new intent Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class); in.putExtra(TAG_VTYPE, forumName); in.putExtra(TAG_VCOLOR, score); in.putExtra(TAG_THANKS, totalThanks); in.putExtra(TAG_POSTS, totalPosts); in.putExtra(TAG_JOIN_DATE, joinDate); in.putExtra(TAG_ROM_COUNT, romCount); in.putExtra(TAG_THEME_COUNT, themeCount); in.putExtra(TAG_MOD_COUNT, modCount); in.putExtra(TAG_KERNEL_COUNT, kernelCount); in.putExtra(TAG_TUTORIAL_COUNT, tutorialCount); in.putExtra(TAG_DEV, recognizedDeveloper); in.putExtra(TAG_THEMER, recognizedThemer); in.putExtra(TAG_MODERATOR, moderator); in.putExtra(TAG_RDEV, recognizedEliteDeveloper); in.putExtra(TAG_RCOD, recognizedContributor); startActivity(in); }});} protected Boolean doInBackground(final String... args) { JSONParser jParser = new JSONParser(); // getting JSON string from URL JSONArray json = jParser.getJSONFromUrl(url); for (int i = 0; i < json.length(); i++) { try { JSONObject c = json.getJSONObject(i); String forumName = c.getString(TAG_VTYPE); String score = c.getString(TAG_VCOLOR); String totalThanks = c.getString(TAG_THANKS); String totalPosts = c.getString(TAG_POSTS); String joinDate = c.getString(TAG_JOIN_DATE); String romCount = c.getString(TAG_ROM_COUNT); String themeCount = c.getString(TAG_THEME_COUNT); String modCount = c.getString(TAG_MOD_COUNT); String kernelCount = c.getString(TAG_KERNEL_COUNT); String tutorialCount = c.getString(TAG_TUTORIAL_COUNT); String recognizedDeveloper = c.getString(TAG_DEV); String recognizedThemer = c.getString(TAG_THEMER); String moderator = c.getString(TAG_MODERATOR); String recognizedEliteDeveloper = c.getString(TAG_RDEV); String recognizedContributor = c.getString(TAG_RCOD); HashMap<String, String> map = new HashMap<String, String>(); // adding each child node to HashMap key => value map.put(TAG_VTYPE, forumName); map.put(TAG_VCOLOR, score); map.put(TAG_THANKS, totalThanks); map.put(TAG_POSTS, totalPosts); map.put(TAG_JOIN_DATE, joinDate); map.put(TAG_ROM_COUNT, romCount); map.put(TAG_THEME_COUNT, themeCount); map.put(TAG_MOD_COUNT, modCount); map.put(TAG_KERNEL_COUNT, kernelCount); map.put(TAG_TUTORIAL_COUNT, tutorialCount); map.put(TAG_DEV, recognizedDeveloper); map.put(TAG_THEMER, recognizedThemer); map.put(TAG_MODERATOR, moderator); map.put(TAG_RDEV, recognizedEliteDeveloper); map.put(TAG_RCOD, recognizedContributor); jsonlist.add(map); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return null; }}} and tied it together with a list view and xml for all my values. turned out really cool. i added an onclick on each value to show more individual data
How to use youtube embed in my application,now its going to youtube site
Actually i am getting url from json,now in my listview its shows all the list of youtube url which was there in json parsing.After clicking the url it is going to youtube page and that video is playing,I dont want to go to othersite from my application,the video has to be shown in my applicaiton,for that how i will use youtube embed in my application. How to show the listof youtube videos in my listview,now it showing the url,I want it has to show the small videos of listview if we click the video it will play the youtube video in my apps using embed Myactivity.java public class PoojaVideos extends Activity implements FetchDataListener1 { private ProgressDialog dialog; ListView lv2; private List<Application1> items; #Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_list_item1); lv2 =(ListView)findViewById(R.id.listV_main); lv2.setOnItemClickListener(new OnItemClickListener() { #Override public void onItemClick(AdapterView<?> a, View v, int position, long id) { Object o = lv2.getItemAtPosition(position); Application1 obj_itemDetails = (Application1)o; final Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(((Application1) o).getUrlWiki())); startActivity(i); } }); //praycount.setOnClickListener(this); initView(); } private void initView(){ // show progress dialog dialog = ProgressDialog.show(this, "", "Loading..."); String url = "http://www.ginfy.com/api/v1/videos.json"; FetchDataTask1 task = new FetchDataTask1(this); task.execute(url); } #Override public void onFetchComplete(List<Application1> data) { this.items = data; // dismiss the progress dialog if ( dialog != null ) dialog.dismiss(); // create new adapter ApplicationAdapter1 adapter = new ApplicationAdapter1(this, data); // set the adapter to list lv2.setAdapter(adapter); } #Override public void onFetchFailure(String msg) { if ( dialog != null ) dialog.dismiss(); Toast.makeText(this, msg, Toast.LENGTH_LONG).show(); } This is the activity for showing listview and after clicking the item in list it is going to youtube page. mylayout.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <ListView android:layout_height="wrap_content" android:layout_width="fill_parent" android:id="#+id/listV_main"/> </LinearLayout> I dont want to go in youtube site,the video has to show in my application itself,for that how to use embed Application Adapter.java public class ApplicationAdapter1 extends ArrayAdapter<Application1> { private List<Application1> items; private LayoutInflater inflator; private PoojaVideos activity; private ProgressDialog dialog; public ApplicationAdapter1(PoojaVideos context, List<Application1> items){ super(context, R.layout.activity_row1, items); this.items = items; inflator = LayoutInflater.from(getContext()); activity=context; } #Override public int getCount(){ return items.size(); } #Override public View getView(int position, View convertView, ViewGroup parent){ ViewHolder holder = null; //View v = convertView; if ( convertView == null ){ convertView = inflator.inflate(R.layout.activity_row1, null); holder = new ViewHolder(); holder.prayersLinkWiki = (TextView) convertView.findViewById(R.id.prayersLinkWiki); convertView.setTag(holder); }else { holder = (ViewHolder) convertView.getTag(); } Application1 app1 = items.get(position); holder.prayersLinkWiki.setText(Html.fromHtml(app1.getUrlWiki())); return convertView; } class ViewHolder { public TextView prayersLinkWiki; } //return convertView; } Fetchdatatask1.java public class FetchDataTask1 extends AsyncTask<String, Void, String> { private final FetchDataListener1 listener; private OnClickListener onClickListener; private String msg; public FetchDataTask1(FetchDataListener1 listener) { this.listener = listener; } #Override protected String doInBackground(String... params) { if ( params == null ) return null; // get url from params String url = params[0]; try { // create http connection HttpClient client = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); // connect HttpResponse response = client.execute(httpget); // get response HttpEntity entity = response.getEntity(); if ( entity == null ) { msg = "No response from server"; return null; } // get response content and convert it to json string InputStream is = entity.getContent(); return streamToString(is); } catch ( IOException e ) { msg = "No Network Connection"; } return null; } #Override protected void onPostExecute(String sJson) { if ( sJson == null ) { if ( listener != null ) listener.onFetchFailure(msg); return; } try { // convert json string to json object JSONObject jsonObject = new JSONObject(sJson); JSONArray aJson = jsonObject.getJSONArray("youtube_url"); // create apps list List<Application1> apps = new ArrayList<Application1>(); for ( int i = 0; i < aJson.length(); i++ ) { JSONObject json = aJson.getJSONObject(i); Application1 app1 = new Application1(); app1.setUrlWiki("https://www.youtube.com/watch?v="+json.getString("youtube_url")); // add the app to apps list apps.add(app1); } //notify the activity that fetch data has been complete if ( listener != null ) listener.onFetchComplete(apps); } catch ( JSONException e ) { e.printStackTrace(); msg = "Invalid response"; if ( listener != null ) listener.onFetchFailure(msg); return; } } /** * This function will convert response stream into json string * * #param is * respons string * #return json string * #throws IOException */ public String streamToString(final InputStream is) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ( (line = reader.readLine()) != null ) { sb.append(line + "\n"); } } catch ( IOException e ) { throw e; } finally { try { is.close(); } catch ( IOException e ) { throw e; } } return sb.toString(); } } this is for the row url showing layout <?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:descendantFocusability="blocksDescendants"> <TextView android:id="#+id/prayersLinkWiki" android:layout_width="wrap_content" android:layout_height="wrap_content" android:autoLink="web" android:textSize="15sp" /> </RelativeLayout> In my listview it will shown the url,after clicking the url it goes to youtube site for video,for the listview in holder url can we use embed for list of youtube videos in this line holder.prayersLinkWiki.setText(Html.fromHtml(app1.getUrlWiki()));
Remove The Code final Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(((Application1) o).getUrlWiki())); startActivity(i); add code to open a dialog with webview. In the webview load youtube URL