dialog box is not dismissing even the images completely loaded - 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();
}
}
}

Related

how to call method in login page

i'm currently trying to make a validation for a login page, which is to validate whether the account is in my database or not, i'm to call the method of invokelogin(), but it seems but i don't know how to call the method, need some help with it.
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
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.List;
public class Activity_Login extends Activity{
private Button btnSignIn;
String username;
String pass;
public static final String USER_NAME = "USERNAME";
EditText txtUser;
EditText Pass;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btnSignIn = (Button) findViewById(R.id.btnSignIn);
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
launchActivity3();
}
});
}
public void launchActivity3() {
txtUser = (EditText) findViewById(R.id.txtUser);
Pass = (EditText) findViewById(R.id.txtPass);
if (txtUser.getText().toString().equals("")) {
Toast.makeText(Activity_Login.this, "UserName must Be Filled", Toast.LENGTH_SHORT).show();
} else if (Pass.getText().toString().equals("")) {
Toast.makeText(Activity_Login.this, "Password must be Filled", Toast.LENGTH_SHORT).show();
} else {
invokeLogin();
}
Intent intent_SignIn = new Intent(Activity_Login.this, Activity_Drawer2.class);
startActivity(intent_SignIn);
}
public void invokeLogin(View view){
username = txtUser.getText().toString();
pass = Pass.getText().toString();
login(username,pass);
}
private void login (final String username, String pass){
class LoginAsync extends AsyncTask<String, Void, String> {
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(Activity_Login.this, "Please wait", "Loading...");
}
#Override
protected String doInBackground(String... params) {
String uname = params[0];
String pass = params[1];
InputStream is = null;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", uname));
nameValuePairs.add(new BasicNameValuePair("password", pass));
String result = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.10.1.11/login.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String result) {
String s = result.trim();
loadingDialog.dismiss();
if (s.equalsIgnoreCase("success")) {
Intent intent = new Intent(Activity_Login.this, Activity_Drawer2.class);
intent.putExtra(USER_NAME, username);
finish();
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Invalid User Name or Password", Toast.LENGTH_LONG).show();
}
}
}
LoginAsync la = new LoginAsync();
la.execute(username, pass);
}
}
You can pass txtUser and Pass to invokeLogin();
so it look like invokeLogin(txtUser,Pass);
Then your invokeLogin method
public void invokeLogin(String username, String pass){
login(username,pass);
}

Add new item on top in custom adapter [closed]

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.

I want to fetch image from mysql to android listview using php json...?

> 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.

Display image from mysql database [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
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();
}
}
}
You can refer the following link http://sunil-android.blogspot.in/2013/10/insert-and-retrieve-image-into-db.html. It will helpfull to you.

How to display image from mysql database?

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

Categories

Resources