Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am not able to Add new item on top in custom adapter in Android. Post CommentPageActivity Class and MyAdapter Class for better understanding.
CommentPageActivity class populate ListView and on onclick action, we are calling MyAdapter
package com.sk.comment;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.sk.bhangarwaala.R;
import com.sk.variable.Globals;
import com.sk.variable.Variable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.app.ActionBar;
import android.app.Activity;
import android.graphics.drawable.ColorDrawable;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class CommentPageActivity extends Activity {
MyAdapter listAdapter;
ListView commentPageLvCommentsList;
TextView commentPageTvSkid,commentPageTvLoader;
EditText commentPageEtEnterComments;
LinearLayout commentPageLlCommentsContainer;
Button commentPageBtSubmit;
List<CommentsFeedObj> data;
String key,json;
boolean isTaskCompleted,isError;
LoadComments task= new LoadComments();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comment_page);
ActionBar actionBar = getActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.my_red)));
// Enabling Back navigation on Action Bar icon
actionBar.setDisplayHomeAsUpEnabled(true);
key=getIntent().getExtras().getString("skid");
System.out.println("CommentPageActivity.onCreate() | key | "+key);
data = new ArrayList<CommentsFeedObj>();
Display d = ((Activity) this).getWindowManager()
.getDefaultDisplay();
int h = d.getHeight();
int w = d.getWidth();
System.out.println("CommentPageActivity.onCreate()|h|"+h+" |w|"+w);
DisplayMetrics displayMetrics = getApplicationContext().getResources().getDisplayMetrics();
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels;
System.out.println("CommentPageActivity.onCreate() |height| "+height);
if(w>h){
height=height*65/100;
}else{
height=height*75/100;
}
System.out.println("CommentPageActivity.onCreate() |height| "+height);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, height);
commentPageLlCommentsContainer = (LinearLayout)findViewById(R.id.commentPageLlCommentsContainer);
commentPageLlCommentsContainer.setLayoutParams(lp);
commentPageTvSkid = (TextView)findViewById(R.id.commentPageTvSkid);
commentPageTvSkid.setVisibility(View.GONE);
commentPageEtEnterComments = (EditText)findViewById(R.id.commentPageEtEnterComments);
System.out.println("CommentPageActivity.onCreate() width | | "+width);
System.out.println("CommentPageActivity.onCreate() | 80/width*100 | "+width*80/100);
commentPageEtEnterComments.setLayoutParams(new LinearLayout.LayoutParams(width*80/100, LinearLayout.LayoutParams.WRAP_CONTENT));
commentPageLvCommentsList = (ListView)findViewById(R.id.commentPageLvCommentsList);
commentPageTvLoader=(TextView)findViewById(R.id.commentPageTvLoader);
initLoadComments();
commentPageBtSubmit = (Button)findViewById(R.id.commentPageBtSubmit);
//commentPageBtSubmit.setBackgroundResource(R.drawable.ic_email_send);
commentPageBtSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
performAddCommentsOperation();
}
});
}
void initLoadComments(){
task.execute();
}
void loadCommentsView(){
try {
if(error)){
CommentsFeedObj obj = new CommentsFeedObj();
obj.setUserProfileImg("");
obj.setUserName("");
obj.setUserMsg("");
obj.setTimestamp("");
obj.setSkid(key);
obj.setResponseStatus("error");
data.add(obj);
}else{
parseJson(new JSONObject(json));
}
listAdapter= new MyAdapter(this, data);
commentPageLvCommentsList.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
}
void parseJson(JSONObject response){
System.out.println("CommentPageActivity.parseJson()");
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
CommentsFeedObj obj = new CommentsFeedObj();
obj.setUserProfileImg(feedObj.getString("userProfileImg"));
obj.setUserName(feedObj.getString("userName"));
obj.setUserMsg(feedObj.getString("userMsg"));
obj.setTimestamp(feedObj.getString("timestamp"));
obj.setSkid(feedObj.getString("skid"));
obj.setLogonUserId(feedObj.getString("logonUserId"));
obj.setLogonUserName(feedObj.getString("logonUserName"));
obj.setLogonUserMobileNumber(feedObj.getString("logonUserMobileNumber"));
obj.setUserLocation(feedObj.getString("userLocation"));
obj.setTs_long(Long.parseLong(feedObj.getString("ts_long")));
obj.setResponseStatus("success");
data.add(obj);
}
System.out.println("CommentPageActivity.parseJson() | "+data);
} catch (JSONException e) {
e.printStackTrace();
}
}
private class LoadComments extends AsyncTask<String, Void, String>{
#Override
protected void onPreExecute(){
super.onPreExecute();
commentPageTvLoader.setVisibility(View.VISIBLE);
commentPageTvLoader.setText("Loading...");
}
#Override
protected void onPostExecute(String result){
int i=0;
while(true){
i=i+1;
if(i==4){json=(Globals._N_LOADING_ERROR_COMMENTS); break;}
if(isTaskCompleted && (json==null || json.length()<1)){
task.execute(Variable.WS_URL_LOAD_COMMENTS);
isTaskCompleted=false;
}else if(isTaskCompleted&& (json!=null || json.length()>0))
{/*prgDialog.dismiss();*/break;}
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
}
}, 200);
}// while
loadCommentsView();
commentPageTvLoader.setVisibility(View.GONE);
}
#Override
protected String doInBackground(String... params) {
System.out.println("CommentPageActivity.LoadComments.doInBackground()");
StringBuffer response=new StringBuffer("");
List<NameValuePair> nameVauePairs=new ArrayList<NameValuePair>(1);
InputStream is=null;
nameVauePairs.add(new BasicNameValuePair("skid", key));
try {
HttpPost httppost = new HttpPost(Variable.WS_URL_LOAD_COMMENTS);
HttpClient httpclient = new DefaultHttpClient();
httppost.setEntity(new UrlEncodedFormEntity(nameVauePairs));
HttpResponse response1 = httpclient.execute(httppost);
StatusLine statusLine= response1.getStatusLine();
System.out.println("CommentPageActivity.LoadComments.doInBackground() | statusLine | "+statusLine);
{
HttpEntity entity =response1.getEntity();
is=entity.getContent();
InputStreamReader in =new InputStreamReader(is);
BufferedReader br = new BufferedReader(in);
String info="";
String nl=System.getProperty("line.separator");
while((info=br.readLine())!=null){
response.append(info.toString()+nl);
}
System.out.println("CommentPageActivity.LoadComments.doInBackground() | response.toString() | "+response.toString());
json=response.toString();
isTaskCompleted=true;
isError=false;
br.close();
}
} catch (UnsupportedEncodingException e) {
isTaskCompleted=true;
isError=true;
e.printStackTrace();
}catch (ClientProtocolException e) {
isTaskCompleted=true;
isError=true;
e.printStackTrace();
} catch (IOException e) {
isTaskCompleted=true;
isError=true;
e.printStackTrace();
}
return "";
}// doBackGroud
}// SaveComment
void performAddCommentsOperation(){
System.out.println("CommentPageActivity.performAddCommentsOperation()");
String msg=commentPageEtEnterComments.getText()+"".trim();
String logonUserName=Globals.getInstance().getLogonUserName();
String logonUserMobileNumber=Globals.getInstance().getLogonUserMobileNumber();
String logonUserId=Globals.getInstance().getLogonUserId();
if(msg==null || msg.length()<1){
Toast.makeText(this, "Please enter comments", Toast.LENGTH_SHORT).show();
commentPageEtEnterComments.setText("");
return;
}
commentPageEtEnterComments.setText("");
if(logonUserName!=null && logonUserName.trim().length()>0){
}else{
logonUserName="unknown";
}
if(msg!=null && msg.trim().length()>0){
}else{
msg="nice shop";
}
CommentsFeedObj obj = new CommentsFeedObj();
obj.setUserProfileImg("");
obj.setUserName(logonUserName);
obj.setUserMsg(msg);
obj.setTimestamp(""+new Date());
obj.setSkid(key);
obj.setLogonUserId(logonUserId);
obj.setLogonUserName(logonUserName);
obj.setLogonUserMobileNumber(logonUserMobileNumber);
obj.setUserLocation("");
obj.setTs_long(System.currentTimeMillis());
data.add(obj);
listAdapter= new MyAdapter(this, data);
//commentPageLvCommentsList.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
performSaveCommentOperation(obj);
}
void performSaveCommentOperation(CommentsFeedObj obj){
new SaveComment().execute(obj);
}
private class SaveComment extends AsyncTask<CommentsFeedObj, Void, String>{
#Override
protected void onPreExecute(){
super.onPreExecute();
}
#Override
protected void onPostExecute(String result){
}
#Override
protected String doInBackground(CommentsFeedObj... params) {
System.out.println("CommentPageActivity.SaveComment.doInBackground()");
StringBuffer response=new StringBuffer("");
List<NameValuePair> nameVauePairs=new ArrayList<NameValuePair>(1);
InputStream is=null;
CommentsFeedObj obj=params[0];
nameVauePairs.add(new BasicNameValuePair("ts_long", obj.getTs_long()+""));
nameVauePairs.add(new BasicNameValuePair("skid", obj.getSkid()));
nameVauePairs.add(new BasicNameValuePair("userName", obj.getUserName()));
nameVauePairs.add(new BasicNameValuePair("timestamp", obj.getTimestamp()));
nameVauePairs.add(new BasicNameValuePair("userProfileImg", obj.getUserProfileImg()));
nameVauePairs.add(new BasicNameValuePair("userMsg", obj.getUserMsg()));
nameVauePairs.add(new BasicNameValuePair("host_name", obj.getHost_name()));
nameVauePairs.add(new BasicNameValuePair("gallery_name", obj.getGallery_name()));
nameVauePairs.add(new BasicNameValuePair("logonUserName", obj.getLogonUserName()));
nameVauePairs.add(new BasicNameValuePair("logonUserMobileNumber", obj.getLogonUserMobileNumber()));
nameVauePairs.add(new BasicNameValuePair("logonUserId", obj.getLogonUserId()));
nameVauePairs.add(new BasicNameValuePair("userLocation", obj.getUserLocation()));
try {
HttpPost httppost = new HttpPost(Variable.WS_URL_SAVE_COMMENTS);
HttpClient httpclient = new DefaultHttpClient();
httppost.setEntity(new UrlEncodedFormEntity(nameVauePairs));
HttpResponse response1 = httpclient.execute(httppost);
StatusLine statusLine= response1.getStatusLine();
System.out.println("CommentPageActivity.SaveComment.doInBackground() | statusLine | "+statusLine);
{
HttpEntity entity =response1.getEntity();
is=entity.getContent();
InputStreamReader in =new InputStreamReader(is);
BufferedReader br = new BufferedReader(in);
String info="";
String nl=System.getProperty("line.separator");
while((info=br.readLine())!=null){
response.append(info.toString()+nl);
}
System.out.println("CommentPageActivity.SaveComment.doInBackground() | response.toString() | "+response.toString());
br.close();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}// doBackGroud
}// SaveComment
/* #Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_comment_page, menu);
return true;
}*/
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
finish();
return true;
}
}
----------------- MyAdapter Class
package com.sk.comment;
import java.util.List;
import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.sk.bhangarwaala.R;
import com.sk.faq.AppController;
import com.sk.variable.Variable;
public class MyAdapter extends BaseAdapter {
private Context activity;
//private LayoutInflater inflater;
private List<CommentsFeedObj> feedItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
private static int counter;
/*public MyAdapter(Activity activity, List<CommentsFeedObj> feedItems) {
this.activity = activity;
this.feedItems = feedItems;
}*/
public MyAdapter(Context applicationContext, List<CommentsFeedObj> data) {
// TODO Auto-generated constructor stub
this.activity = applicationContext;
this.feedItems = data;
//inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
if(feedItems!=null)
return feedItems.size();
return 0;
}
#Override
public Object getItem(int location) {
return feedItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressLint("DefaultLocale")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
CompleteListViewHolder viewHolder;
View v = convertView;
counter=counter+1;
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
if (convertView == null){
LayoutInflater li = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = li.inflate(R.layout.comment_page_list_comments, null);
viewHolder = new CompleteListViewHolder(v);
v.setTag(viewHolder);
}else{
viewHolder = (CompleteListViewHolder) v.getTag();
}
CommentsFeedObj item = feedItems.get(position);
System.out.println("MyAdapter.getView() | item | "+item.toString());
// sk id
viewHolder.commentPageTvSkid.setText(item.getSkid());
viewHolder.commentPageTvSkid.setVisibility(View.GONE);
// user profile img
if (item.getUserProfileImg()!=null && !item.getUserProfileImg().equalsIgnoreCase("null") && item.getUserProfileImg().length() >0){ // 1
String img=item.getHost_name()+"/"+item.getGallery_name()+"/"+item.getUserProfileImg();
System.out.println("MyAdapter.getView() | img | "+img);
viewHolder.commentPageNivProfileImg.setImageUrl(img, imageLoader);
}else{
System.out.println("MyAdapter.getView() | DEFAULT_PROFILE_IMG | "+imageLoader);
viewHolder.commentPageNivProfileImg.setImageUrl(Variable.DEFAULT_PROFILE_IMG, imageLoader);// 1
}
// user name
viewHolder.commentPageTvUserName.setText(item.getUserName().toUpperCase());
// time stamp
viewHolder.commentPageTvTimestamp.setText(item.getTimestamp());
// user msg
if(item.getUserMsg()!=null){
viewHolder.commentPageTvUserMsg.setText(item.getUserMsg());
}else{
viewHolder.commentPageTvUserMsg.setVisibility(View.GONE);
}
return v;
}
}//MainClass
class CompleteListViewHolder {
//http://androidadapternotifiydatasetchanged.blogspot.in/
TextView commentPageTvUserName,commentPageTvTimestamp,commentPageTvUserMsg ,commentPageTvSkid ;
NetworkImageView commentPageNivProfileImg ;
public CompleteListViewHolder(View convertView) {
commentPageTvUserName = (TextView) convertView.findViewById(R.id.commentPageListCommentsTvUserName);
commentPageTvTimestamp = (TextView) convertView.findViewById(R.id.commentPageListCommentsTvTimestamp);
commentPageTvUserMsg = (TextView) convertView.findViewById(R.id.commentPageListCommentsTvUserMsg);
commentPageTvSkid = (TextView) convertView.findViewById(R.id.commentPageListCommentsTvSkid);
commentPageNivProfileImg = (NetworkImageView) convertView.findViewById(R.id.commentPageListCommentsNivProfileImg);
}
}
When you add new commnent, always add this comment at the beginning of your data. Then refresh you ListView
data.add(0, commnent);
listAdapter.notifyDataSetChanged();
You can you this before init new Adapter:
data.add(0, value);
This will add new value in the begin of your list.
Finally done, I have used this data.add(0,obj) instead of data.add(obj) on onClick Action.
void onClickCommentButton(){
data.add(0,obj);
listAdapter= new MyAdapter(this, data);
commentPageLvCommentsList.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
}
You will be able to do by adding header at top. There should be methods with adapterView or list. I had done last year . It allows only one header item per list though I remember.
Related
I'm working on an app and I'm trying to show a listview filled with information from a MySQL database. I already have a different activity where I send and receive from the database using php, I'm doing something similar. I'm not sure if the error I'm having is something with the adapter class or from the Json Parsing part in the AsyncTask. These are the files:
package com.example.xxx.xxx;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
public class ListActivity extends ActionBarActivity {
ListView list;
ArrayList<Places> placeslist;
PlacesAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_row);
placeslist = new ArrayList<Places>();
new JASONTask().execute("http://xxx.xxx.com/getlist.php");
adapter = new PlacesAdapter(getApplicationContext(), R.layout.single_row, placeslist);
list = (ListView)findViewById(R.id.listView);
list.setAdapter(adapter);
}
public class JASONTask extends AsyncTask<String,Void,Boolean>{
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(ListActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line ="";
while ((line = reader.readLine()) != null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONArray theJson = new JSONArray(finalJson);
for (int i=0; i<theJson.length(); i++){
Places place = new Places();
JSONObject jRealObject = theJson.getJSONObject(i);
place.setPlaces_id(jRealObject.getString("places_id"));
place.setName(jRealObject.getString("name"));
place.setLocation_address(jRealObject.getString("location_address"));
placeslist.add(place);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if(connection != null) {
connection.disconnect();
}
try {
if (reader != null){
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if (result == false){
//message not parsed
}
}
}
}
The Places class is:
package com.example.xxx.xxx;
/**
* Created by manhols on 10/12/2015.
*/
public class Places {
private String places_id;
private String name;
private String location_address;
public Places(){
}
public String getPlaces_id() {
return places_id;
}
public void setPlaces_id(String places_id) {
this.places_id = places_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation_address() {
return location_address;
}
public void setLocation_address(String location_address) {
this.location_address = location_address;
}
}
And the PlacesAdapter class is:
package com.example.xxx.xxx;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by manhols on 10/12/2015.
*/
public class PlacesAdapter extends ArrayAdapter<Places>{
ArrayList<Places> placeslist;
int Resource;
Context context;
LayoutInflater vi;
public PlacesAdapter(Context context, int resource, ArrayList<Places> objects) {
super(context, resource, objects);
Resource = resource;
placeslist = objects;
vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
vi.inflate(Resource, null);
convertView = vi.inflate(Resource,null);
holder = new ViewHolder();
holder.textView = (TextView)convertView.findViewById(R.id.textView);
holder.textView2 = (TextView)convertView.findViewById(R.id.textView2);
holder.textView5 = (TextView)convertView.findViewById(R.id.textView5);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
holder.textView.setText(placeslist.get(position).getName());
holder.textView2.setText(placeslist.get(position).getPlaces_id());
holder.textView5.setText(placeslist.get(position).getLocation_address());
return convertView;
}
static class ViewHolder {
public TextView textView;
public TextView textView2;
public TextView textView5;
}
}
I will highly appreciate any help solving this issue.
I have spotted some errors in your adapter. Please inflate row as convertView = vi.inflate(Resource,parent,false); and also in parsing the data , return true only in try block. From your code i can see that even if you have an exception, you will be returning true which is wrong.
My problem was in the setContentView as #codeMagic mentioned before. I already solved this thanks to him
The following code when run crashes my app. I am calling it in the MainActivity. When run it tells me:
FATAL EXCEPTION: AsyncTask #1 and directs me toward the ProgressDialog and Http Response Line
import android.app.Fragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import com.montel.senarivesselapp.model.ShowDataList;
import com.montel.senarivesselapp.model.Vessel;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
public class ShowallFragment extends Fragment {
//variables for JSON query
private static final String name ="vessel_name";
private static final String etad="eta_date";
private static final String etat="eta_time";
private static final String etbd="etb_date";
private static final String etbt="etb_time";
private static final String shippingName="shipping_agent_name";
private static final String v1 = "vessels";
private static final String v2 = "Vessel";
private ArrayList<Vessel> vList = new ArrayList<>();
private ArrayAdapter arrayAdapter = null;
private ListView listView = null;
private EditText et = null;
private ShowDataList ssadapter = null;
private View rootView;
public ShowallFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_showall, container, false);
setContentView(R.layout.fragment_showall);
setRetainInstance(true);
return rootView;
}
private void setContentView(int fragment_showall) {
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
//For getting the JSON schedule from server
class Schedule extends AsyncTask<String, String, String> {
ProgressDialog loadDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
//Show the loading dialog
loadDialog = new ProgressDialog(ShowallFragment.this);
loadDialog.setMessage("Please wait....");
loadDialog.setCancelable(false);
loadDialog.show();
}
#Override
protected String doInBackground(String... uri) {
BufferedReader input = null;
String data = null;
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(new HttpGet("http://"));
StatusLine stline = response.getStatusLine();
if (stline.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
data = out.toString();
out.close();
} else {
response.getEntity().getContent().close();
throw new IOException(stline.getReasonPhrase());
}
} catch (HttpResponseException he) {
he.printStackTrace();
} catch (ClientProtocolException cpe) {
cpe.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
return data;
} catch (Exception e) {
System.out.println(e);
}
}
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Fill the vList array
Log.d("POST EXECUTE", result.toString());
loadDialog.dismiss();
if (result != null) {
try {
JSONObject jo = new JSONObject(result);
JSONArray vessels = jo.getJSONArray(v1);
Log.d("VESSEL LOG", vessels.toString());
vList = new ArrayList();
for (int i = 0; i < vessels.length(); i++) {
JSONObject vv = vessels.getJSONObject(i);
Log.d("VESSEL NAME", vv.getJSONObject(v2).getString(name));
vList.add(new Vessel(vv.getJSONObject(v2).getString(name),
vv.getJSONObject(v2).getString(etad),
vv.getJSONObject(v2).getString(etat),
vv.getJSONObject(v2).getString(etbd),
vv.getJSONObject(v2).getString(etbt),
vv.getJSONObject(v2).getString(shippingName)));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
listView = (ListView) rootView.findViewById(R.id.dataShow);
listView.setAdapter(arrayAdapter);
ssadapter = new ShowDataList(ShowallFragment.this , vList);
listView.setAdapter(ssadapter);
}
}
}
SecurityException: Permission denied (missing INTERNET permission
So you should request INTERNET permission in your projects AndroidManifest.xml file. Add on the rigth place:
<uses-permission android:name="android.permission.INTERNET" />
in your onPostExecute() change the position of Log.d("POST EXECUTE", result.toString()); to be inside catch so your code will look like this:
catch (Exception ee) {
ee.printStackTrace();
}
catch (JSONException e) {
Log.d("POST EXECUTE", e.toString());
} // catch (JSONException e)
> This is my MainActivity.java That receives all json data from the php file and converts into string format and print it in listview using string array but i have problem with bitmap image array
I want to add multiple items in listview like textview and image i dont have problem with textview it displays properly but with image it is not done
package com.demo.php.listview;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore.Images;
import android.util.Base64;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnItemClickListener {
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb = null;
ArrayList<String> al = new ArrayList<String>();
ArrayList<String> al1 = new ArrayList<String>();
ArrayList<String> al2 = new ArrayList<String>();
ArrayList<String> al3=new ArrayList<String>();
String targetmonth;
String targetyear;
String targetamount;
String Dphoto;
// int responseCode;
//int listItemCount=0;
ListView listview ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(Color.WHITE);
setTitleColor(Color.rgb(0x74, 0, 0x37));
setTitle("Doctor's List");
requestWindowFeature(Window.FEATURE_RIGHT_ICON);
setContentView(R.layout.main);
listview = (ListView) findViewById(R.id.listView1);
listview.setOnItemClickListener(this);
new LoadData().execute();
}
private class LoadData extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
#Override
// can use UI thread here
protected void onPreExecute() {
this.progressDialog = ProgressDialog.show(MainActivity.this, ""," Loading...");
}
#Override
protected void onPostExecute(final Void unused) {
try{
listview.setAdapter(new DataAdapter(MainActivity.this,
al.toArray(new String[al.size()]),
al1.toArray(new String[al1.size()]),
al2.toArray(new String[al2.size()]),
al3.toArray(new Bitmap[al3.size()])));
this.progressDialog.dismiss();
}
catch(Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// HTTP post
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
HttpClient httpclient = new DefaultHttpClient();
try{
HttpPost httppost = new HttpPost("http://10.0.2.2/android/test.php");
StringEntity se = new StringEntity("envelope",HTTP.UTF_8);
httppost.setEntity(se);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 3000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
//buffered reader
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 80);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
}
catch(Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
try{
jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
targetamount=json_data.getString("DName");
targetmonth=json_data.getString("Dspl");
targetyear = json_data.getString("Dedu");
Dphoto = json_data.getString("Dphoto");
al.add(targetmonth);
al1.add(targetyear);
al2.add(targetamount);
al3.add(Dphoto);
//listItemCount=al2.size();
}
}
catch(JSONException e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
} catch (ParseException e) {
// Log.e("log_tag", "Error in http connection" + e.toString());
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
catch (Exception e) {
// Log.e("log_tag", "Error in http connection" + e.toString());
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
return null;
}
}
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
Intent intent = new Intent(this, NextItem.class);
startActivity(intent);
}
}
>This is my DataAdapter
I am not getting the image in Listview I am little bit confuse about the image bitmap array please helps with that bitmap
package com.demo.php.listview;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.provider.MediaStore.Images;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class DataAdapter extends BaseAdapter {
Context mContext;
private LayoutInflater mInflater;
String targetmonth;
String targetyear;
String targetamount;
//Bitmap Dphoto1;
String[] month;
String[] year;
String[] amount;
String[] Dphoto1;
Bitmap[] Dphoto2;
private String src;
public DataAdapter(Context c, String[] month, String[] year, String[] amount,Bitmap[] Dphoto2) {
//this.sta = sta;
Bitmap[] = (Bitmap[]) getBitmapFromURL(Dphoto2);
this.month = month;
this.year = year;
this.amount = amount;
this.Dphoto2=Dphoto2;
mContext = c;
mInflater = LayoutInflater.from(c);
}
public int getCount() {
return month.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.doctor, parent, false);
holder = new ViewHolder();
holder.month = (TextView) convertView
.findViewById(R.id.Dname);
holder.year = (TextView) convertView.findViewById(R.id.Dspl);
holder.amount = (TextView) convertView
.findViewById(R.id.Dedu);
holder.Dphoto2=(ImageView)convertView.findViewById(R.id.Dphoto2);
if (position == 0) {
convertView.setTag(holder);
}
} else {
holder = (ViewHolder) convertView.getTag();
}
try {
holder.month.setText(month[position]);
holder.year.setText(year[position]);
holder.amount.setText(amount[position]);
holder.Dphoto2.setImageBitmap(Dphoto2[position]);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return convertView;
}
private Object getBitmapFromURL(Bitmap[] dphoto2) {
// TODO Auto-generated method stub
try{
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
}
static class ViewHolder {
public ImageView Dphoto2;
public TextView Dphoto1;
public ImageView Dphoto;
TextView month;
TextView year, amount;
}
public class ImageLoadTask {
public void execute(String dphoto1) {
// TODO Auto-generated method stub
}
}}
The JSON text will deliver a base64 encoded bitmap or jpg.
ArrayList<String> al3=new ArrayList<String>();
change that to:
ArrayList<Bitmap> al3=new ArrayList<Bitmap>();
And in the loop change:
al3.add(Dphoto);
to:
Bitmap bitmap = decodeBitmapFromBase64 (Dphoto);
al3.add(bitmap);
Remove:
Bitmap[] = (Bitmap[]) getBitmapFromURL(Dphoto2); // does not even compile!
You have to implement a function decodeBitmapFromBase64(). You can find code for it on this site.
Remove all Toast()s from doInBackground. They are not allowed there. Put them in onPostExecute instead.
I have code to display all data from MySQL databae also i have a image field in MySQL database which have image names.how can i display image from database(The image is located at localhost folder). Im new in android so please help me. Here is my code if u can alter my required code then it will be a great help.
JAVA
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class News_events extends Fragment {
private String jsonResult;
private String url = "http://192.168.2.7/crescentnews/select.php";
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
InputStream is=null;
String result=null;
String line=null;
int code;
public News_events(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_news_events, container, false);
accessWebService();
return rootView;
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getActivity().getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
display();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void display() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("news_details");
LinearLayout MainLL= (LinearLayout)getActivity().findViewById(R.id.newslayout);
//LinearLayout headLN=(LinearLayout)findViewById(R.id.headsection);
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
final String head = jsonChildNode.optString("title");
final String details = jsonChildNode.optString("text");
final String date = jsonChildNode.optString("date");
//final String time = jsonChildNode.optString("time");
TextView headln = new TextView(this.getActivity());
headln.setText(head); // News Headlines
headln.setTextSize(20);
headln.setTextColor(Color.BLACK);
headln.setGravity(Gravity.CENTER);
headln.setBackgroundResource(R.drawable.menubg);
headln.setPadding(10, 20, 10, 0);
headln.setWidth(100);
headln.setClickable(true);
headln.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Toast.makeText(getBaseContext(), head, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity().getApplicationContext(),MainActivity.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
ImageView photo=new ImageView(this.getActivity());
//dateln.setBackgroundColor(Color.parseColor("#f20056"));
photo.setBackgroundColor(Color.parseColor("#000000"));
photo.setPadding(0, 0, 10, 10);
photo.setClickable(true);
TextView dateln = new TextView(this.getActivity());
dateln.setText(date); // News Headlines
dateln.setTextSize(12);
dateln.setTextColor(Color.BLACK);
dateln.setGravity(Gravity.RIGHT);
//dateln.setBackgroundColor(Color.parseColor("#f20056"));
dateln.setBackgroundColor(0x00000000);
dateln.setPadding(0, 0, 10, 10);
dateln.setWidth(100);
dateln.setClickable(true);
dateln.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity().getApplicationContext(), MainActivity.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
View sep=new View(this.getActivity());
sep.setBackgroundColor(Color.parseColor("#252525"));
sep.setMinimumHeight(10);
TextView detailsln = new TextView(this.getActivity());
detailsln.setText(details); // News Details
detailsln.setTextSize(12);
detailsln.setTextColor(Color.BLACK);
detailsln.setGravity(Gravity.LEFT);
detailsln.setPadding(10, 10, 10, 10);
MainLL.addView(headln);
MainLL.addView(dateln);
MainLL.addView(photo);
MainLL.addView(detailsln);
MainLL.addView(sep);
detailsln.setClickable(true);
detailsln.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity().getApplicationContext(), MainActivity.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
}
} catch (JSONException e) {
Toast.makeText(getActivity().getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
}
}
save your image url in db (if they are in a same folder on your host choose a base url and save only image name)
after fetching your data , there are alot of library for display images such as :
Picasso
A powerful image downloading and caching library for Android
Here is my code for fetching and loading some datas and images from mysql database in a loop,The problem is the dialog box "Loading image " is not dismissing even after the images completely loaded.
I'm new in android,Please anybody help me.
Java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class News_events extends Fragment {
private String jsonResult;
private String url = "http://192.168.2.7/crescentnews/select.php";
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
ImageView img;
Bitmap bitmap;
ProgressDialog pDialog;
InputStream is=null;
String result=null;
String line=null;
int code;
public News_events(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_news_events, container, false);
accessWebService();
return rootView;
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getActivity().getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
display();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void display() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("news_details");
LinearLayout MainLL= (LinearLayout)getActivity().findViewById(R.id.newslayout);
//LinearLayout headLN=(LinearLayout)findViewById(R.id.headsection);
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
final String head = jsonChildNode.optString("title");
final String details = jsonChildNode.optString("text");
final String date = jsonChildNode.optString("date");
final String image = jsonChildNode.optString("img");
//final String time = jsonChildNode.optString("time");
//img = new ImageView(this.getActivity());
//new LoadImage().execute("http://192.168.2.7/crescentnews/images/"+image);
img = new ImageView(this.getActivity());
LoadImage ldimg=new LoadImage();
ldimg.setImage(img);
ldimg.execute("http://192.168.2.7/crescentnews/images/"+image);
TextView headln = new TextView(this.getActivity());
headln.setText(head); // News Headlines
headln.setTextSize(20);
headln.setTextColor(Color.BLACK);
headln.setGravity(Gravity.CENTER);
headln.setBackgroundResource(R.drawable.menubg);
headln.setPadding(10, 20, 10, 0);
headln.setWidth(100);
headln.setClickable(true);
headln.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Toast.makeText(getBaseContext(), head, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity().getApplicationContext(),MainActivity.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
ImageView photo=new ImageView(this.getActivity());
//dateln.setBackgroundColor(Color.parseColor("#f20056"));
photo.setBackgroundColor(Color.parseColor("#000000"));
photo.setPadding(0, 0, 10, 10);
photo.setClickable(true);
// Drawable drawable = LoadImageFromWebOperations("http://192.168.2.7/crescentnews/images/"+pic);
// userpic.setImageDrawable(drawable);
TextView dateln = new TextView(this.getActivity());
dateln.setText(date); // News Headlines
dateln.setTextSize(12);
dateln.setTextColor(Color.BLACK);
dateln.setGravity(Gravity.RIGHT);
//dateln.setBackgroundColor(Color.parseColor("#f20056"));
dateln.setBackgroundColor(0x00000000);
dateln.setPadding(0, 0, 10, 10);
dateln.setWidth(100);
dateln.setClickable(true);
dateln.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity().getApplicationContext(), MainActivity.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
View sep=new View(this.getActivity());
sep.setBackgroundColor(Color.parseColor("#252525"));
sep.setMinimumHeight(10);
TextView detailsln = new TextView(this.getActivity());
detailsln.setText(details); // News Details
detailsln.setTextSize(12);
detailsln.setTextColor(Color.BLACK);
detailsln.setGravity(Gravity.LEFT);
detailsln.setPadding(10, 10, 10, 10);
MainLL.addView(headln);
MainLL.addView(dateln);
MainLL.addView(photo);
MainLL.addView(img);
MainLL.addView(detailsln);
MainLL.addView(sep);
detailsln.setClickable(true);
detailsln.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity().getApplicationContext(), MainActivity.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
}
} catch (JSONException e) {
Toast.makeText(getActivity().getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
ImageView img;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading Image ....");
pDialog.show();
}
public void setImage(ImageView img ){
this.img=img;
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).openStream());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
img.setImageBitmap(image);
}
pDialog.dismiss();
}
}
}