Need help regarding integrating android functions with premade views - android

I'm just new to android and java and i m trying to build a sample android application.
I picked up application view from androhive looks like google+ app
and made my function following to many tutorials online
but i'm unable to integrate them.
here are my codes
Here is my fragment sample which is used in switching activity using sidebar
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MHEFragment extends Fragment {
public MHEFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
return rootView;
}
}
Heres my function os listview
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
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.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
private String jsonResult;
private String url = "http://192.168.129.1/1.php";
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView1);
accessWebService();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
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(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrwaer();
}
}// 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 ListDrwaer() {
List<Map<String, String>> storyList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("story");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("story_name");
String number = jsonChildNode.getString("story_id").toString();
String outPut = number + "-" + name;
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View name, int position,
long number) {
Intent intnt = new Intent(getApplicationContext(), Tester.class);
String deta = adapter.getItemAtPosition(position).toString();
String myStr = deta.replaceAll( "[^\\d]", "" );
intnt.putExtra(EXTRA_MESSAGE,myStr);
startActivity(intnt);
}
});
storyList.add(createStory("stories", outPut));
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
SimpleAdapter simpleAdapter = new SimpleAdapter(this, storyList,
android.R.layout.simple_list_item_1,
new String[] { "stories" }, new int[] { android.R.id.text1 });
listView.setAdapter(simpleAdapter);
}
private HashMap<String, String> createStory(String name, String number) {
HashMap<String, String> storyNameNo = new HashMap<String, String>();
storyNameNo.put(name, number);
return storyNameNo;
}
}
How can i integrate my listview in above fragment?

If you want ListView in fragment then you'd be better off using your Fragment which would subclass ListFragment.
And the onCreateView() from ListFragment will return a ListView that you can populate.
http://developer.android.com/reference/android/app/ListFragment.html
http://www.vogella.com/tutorials/AndroidListView/article.html#listfragments
For Fragments, if you want a separate ListView and more in one fragment, it'l help if you go through:
http://www.easyinfogeek.com/2013/07/full-example-of-using-fragment-in.html
..for what is more to the layout and calling onCreateView()
Also, (not a part of the question, but from & for your code) if it helps, i'd suggest
Use a for each loop where you can instead of for(;;)
(in your case at: for each json child node in json main node)
http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html
How does the Java 'for each' loop work?

Related

Listview to get all data in list in JSON format

I using listview to display the response from API, which is a JSON object. Below listview, a button will be there. On clicking that button I need to get all the data from listview in JSON format.
Activity Class
package com.aryvart.myaromasupply;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ListView;
import com.aryvart.myaromasupply.Adapter.CartListAdapterKV;
import com.aryvart.myaromasupply.Bean.CommonBean;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
/**
* Created by android01 on 28/8/17.
*/
public class CartPageKV extends Activity implements MyInterface {
String json = null;
List<CommonBean> movieList = new ArrayList<>();
RecyclerView recyclerView;
CartListAdapterKV mAdapter;
Context context;
CoordinatorLayout coordinatorLayout;
Button btn_submit;
HashMap<String, JSONObject> hsFilterGmap;
String value;
JSONArray jsonArray;
ListView llView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cart_page_kv);
context = this;
recyclerView = (RecyclerView) findViewById(R.id.my_recyclerView);
btn_submit = (Button) findViewById(R.id.btn_submit);
coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinator_layout);
llView = (ListView) findViewById(R.id.ll_view);
loadJSONFromAsset();
//Response API
try {
JSONObject obj = new JSONObject(json);
Log.e("NN", "json-->" + obj.toString());
JSONArray respArray = obj.getJSONArray("results");
Log.e("NN", "respArray-->" + respArray.toString());
for (int i = 0; i < respArray.length(); i++) {
JSONObject jsonObj = respArray.getJSONObject(i);
CommonBean drawerBean = new CommonBean();
drawerBean.setStr_cart_id(jsonObj.getString("id"));
drawerBean.setStr_cart_title(jsonObj.getString("name"));
drawerBean.setStr_quan(jsonObj.getString("quantity"));
drawerBean.setStr_tot_quant(jsonObj.getString("total_quantity"));
movieList.add(drawerBean);
}
// Getting adapter by passing xml data ArrayList
mAdapter = new CartListAdapterKV(movieList, context, (MyInterface) context);
llView.setAdapter(mAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
//Button Click Event
btn_submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e("NN:fc", String.valueOf(hsFilterGmap));
Iterator myVeryOwnIterator = hsFilterGmap.keySet().iterator();
JSONArray jsonArray = new JSONArray();
while (myVeryOwnIterator.hasNext()) {
String key = (String) myVeryOwnIterator.next();
JSONObject value1 = hsFilterGmap.get(key);
Log.e("NN:value", value1.toString());
jsonArray.put(value1);
}
Log.e("NN:fcAr", jsonArray.toString().replaceAll("\\\\", ""));
System.out.println("the JSON ARRAY is" + jsonArray.toString());
}
});
}
public String loadJSONFromAsset() {
try {
InputStream is = getAssets().open("data.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
// Interface to get Checked value from listview(Hashmap for not allowing duplicates)
#Override
public HashMap<String, JSONObject> getUnCheckedVal(HashMap<String, JSONObject> strVal, String str_removed_id) {
hsFilterGmap = strVal;
Log.e("NN:fc", String.valueOf(hsFilterGmap));
return hsFilterGmap;
}
}
Adapter Class
package com.aryvart.myaromasupply.Adapter;
import android.content.Context;
import android.support.v7.widget.CardView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import com.aryvart.myaromasupply.Bean.CommonBean;
import com.aryvart.myaromasupply.MyInterface;
import com.aryvart.myaromasupply.R;
import com.like.LikeButton;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.List;
/**
* Created by android01 on 28/8/17.
*/
public class CartListAdapterKV extends BaseAdapter {
private List<CommonBean> commonBeanList;
Context c;
MyInterface my_interface;
private static LayoutInflater inflater = null;
HashMap<String, JSONObject> hsMap = new HashMap<String, JSONObject>();
// constructor
public CartListAdapterKV(List<CommonBean> movieList, Context context, MyInterface inter) {
this.commonBeanList = movieList;
Log.e("NN", "size-->" + this.commonBeanList);
this.c = context;
this.my_interface = inter;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return commonBeanList.size();
}
public Object getItem(int position) {
return commonBeanList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (convertView == null)
view = inflater.inflate(R.layout.cart_items_kv, parent, false);
TextView txt_cartTitle;
final CheckBox cb_box;
txt_cartTitle = (TextView) view.findViewById(R.id.textView2);
cb_box = (CheckBox) view.findViewById(R.id.checkBoxKV);
final CommonBean recyclerBean = commonBeanList.get(position);
cb_box.setChecked(true);
txt_cartTitle.setText(recyclerBean.getStr_cart_title());
//check if checkbox is checked. if yes the add value to hashmap(by default all checkboxes will be checked in listview
if (cb_box.isChecked()) {
Toast.makeText(c, "--" + recyclerBean.getStr_cart_title(), Toast.LENGTH_SHORT).show();
//JSONArray req = new JSONArray();
JSONObject jsoBj = new JSONObject();
try {
jsoBj.put("id", recyclerBean.getStr_cart_id());
jsoBj.put("value", recyclerBean.getStr_cart_title());
jsoBj.put("checked", "true");
} catch (JSONException e) {
e.printStackTrace();
}
hsMap.put(recyclerBean.getStr_cart_id(), jsoBj);
my_interface.getUnCheckedVal(hsMap, recyclerBean.getStr_cart_id());
Log.e("NN", "AdpaMap--" + hsMap.toString());
} else {
JSONObject jsoBj = new JSONObject();
try {
jsoBj.put("id", recyclerBean.getStr_cart_id());
jsoBj.put("value", recyclerBean.getStr_cart_title());
jsoBj.put("checked", "false");
} catch (JSONException e) {
e.printStackTrace();
}
//adding the json object in hashmap to remove duplicates
hsMap.put(recyclerBean.getStr_cart_id(), jsoBj);
my_interface.getUnCheckedVal(hsMap, recyclerBean.getStr_cart_id());
Toast.makeText(c, "-*-" + recyclerBean.getStr_cart_title(), Toast.LENGTH_SHORT).show();
}
cb_box.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
final CommonBean recyclerBean = commonBeanList.get(position);
if (cb_box.isChecked()) {
Toast.makeText(c, "--" + recyclerBean.getStr_cart_title(), Toast.LENGTH_SHORT).show();
JSONObject jsoBj = new JSONObject();
try {
jsoBj.put("id", recyclerBean.getStr_cart_id());
jsoBj.put("value", recyclerBean.getStr_cart_title());
jsoBj.put("checked", "true");
} catch (JSONException e) {
e.printStackTrace();
}
hsMap.put(recyclerBean.getStr_cart_id(), jsoBj);
my_interface.getUnCheckedVal(hsMap, recyclerBean.getStr_cart_id());
Log.e("NN", "AdpaMap--" + hsMap.toString());
} else {
JSONObject jsoBj = new JSONObject();
try {
jsoBj.put("id", recyclerBean.getStr_cart_id());
jsoBj.put("value", recyclerBean.getStr_cart_title());
jsoBj.put("checked", "false");
} catch (JSONException e) {
e.printStackTrace();
}
hsMap.put(recyclerBean.getStr_cart_id(), jsoBj);
my_interface.getUnCheckedVal(hsMap, recyclerBean.getStr_cart_id());
Toast.makeText(c, "-*-" + recyclerBean.getStr_cart_title(), Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
}
On initial clicking of a button, I'm getting the data which is in the foreground (visible to the user), once I scroll remaining data's are getting.
Can anyone help how can I get entire values in listview in on button click?
Open this cart_items_kv xml and place the button.
Go to the adapter
and make the event there.You can get the data of an item by position in adapter.
another solution
add a click after finding view
public ViewHolder(View itemLayoutView) {
// here `enter code here`
itemLayoutView.setOnClickListener(this);
}

Images are not loading in GridView using picasso 2.5.2

Currently I am developing a Popular Movies app by udacity and stuck at loading images from the MovieDb api. I have also took reference from this thread Picasso Images are not loading in Gridview Android but no use.
Here is my fragment file:
package com.akshitjain.popularmovies;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
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.URL;
/**
* A placeholder fragment containing a simple view.
*/
public class MainActivityFragment extends Fragment {
ImageAdapter mMoviesAdapter;
public MainActivityFragment() {
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_main, container, false);
GridView gridview = (GridView) rootView.findViewById(R.id.grid_view_movies);
mMoviesAdapter = new ImageAdapter(getActivity());
gridview.setAdapter(mMoviesAdapter);
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(getActivity(), "" + position,
Toast.LENGTH_SHORT).show();
}
});
return rootView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_mainfragment,menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.action_refresh){
String sortOrder = "popularity.desc";
new FetchMoviesTask().execute(sortOrder);
return true;
}
return super.onOptionsItemSelected(item);
}
public class FetchMoviesTask extends AsyncTask<String, Void, String[]> {
private final String LOG_TAG = FetchMoviesTask.class.getSimpleName();
private String[] getMoviesDataFromJson(String moviesJsonStr)
throws JSONException {
final String TMDB_RESULTS = "results";
final String TMDB_POSTER = "poster_path";
JSONObject moviesJson = new JSONObject(moviesJsonStr);
JSONArray moviesArray = moviesJson.getJSONArray(TMDB_RESULTS);
String[] resultStrs = new String[moviesArray.length()];
for(int i=0;i<moviesArray.length();++i) {
JSONObject movieObject = moviesArray.getJSONObject(i);
resultStrs[i] = movieObject.getString(TMDB_POSTER);
}
return resultStrs;
}
#Override
protected String[] doInBackground(String... params) {
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String moviesJsonStr;
String apiKey = BuildConfig.THE_MOVIE_DB_API_KEY;
try {
// Construct the URL for the TheMovieDb query
// Possible parameters are available at TheMovieDb API page
final String MOVIES_BASE_URL = "http://api.themoviedb.org/3/discover/movie?";
final String SORT_PARAM = "sort_by";
final String API_KEY = "api_key";
Uri builtUri = Uri.parse(MOVIES_BASE_URL).buildUpon()
.appendQueryParameter(SORT_PARAM,params[0])
.appendQueryParameter(API_KEY,apiKey)
.build();
URL url = new URL(builtUri.toString());
Log.v(LOG_TAG,"BuiltUri: " + builtUri.toString());
// Create the request to TheMovieDb, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuilder buffer = new StringBuilder();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line).append("\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
moviesJsonStr = buffer.toString();
Log.v(LOG_TAG,"Movies Json String: " + moviesJsonStr);
} catch (IOException e) {
Log.e("MainActivityFragment", "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attempting
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("MainActivityFragment", "Error closing stream", e);
}
}
}
try{
return getMoviesDataFromJson(moviesJsonStr);
}catch (JSONException e){
Log.e(LOG_TAG,e.getMessage(),e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String[] strings) {
if(strings != null){
mMoviesAdapter.clear();
for(String moviesStr:strings){
mMoviesAdapter.add(moviesStr);
}
}
mMoviesAdapter.notifyDataSetChanged();
super.onPostExecute(strings);
}
}
}
Here is my custom adapter file:
package com.akshitjain.popularmovies;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
public class ImageAdapter extends BaseAdapter {
private final String LOG_TAG = ImageAdapter.class.getSimpleName();
private Context mContext;
List<String> list = new ArrayList<>();
public ImageAdapter(Context c) {
this.mContext = c;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.grid_item_movies, parent, false);
}
final String POSTER_BASE_URL = " http://image.tmdb.org/t/p/";
final String POSTER_SIZE = "w185";
ImageView moviePoster = (ImageView) convertView.findViewById(R.id.grid_item_movie_image);
final String POSTER_FINAL_URL = POSTER_BASE_URL + POSTER_SIZE + list.get(position);
Log.v(LOG_TAG,"Poster Urls: " + POSTER_FINAL_URL);
Picasso.with(mContext).load(POSTER_FINAL_URL).into(moviePoster);
return convertView;
}
public void add(String s) {
list.add(s);
}
public void clear() {
list.clear();
}
}
There is no error in the code. App runs successfully. But images are not loading.
final String POSTER_BASE_URL = " http://image.tmdb.org/t/p/";
The space at the beginning of the string was the issue. Picasso will try and load url with space at front.
So String.trim() will remove the space from the beginning as well as the end of a String.
Picasso.with(mContext).load(POSTER_FINAL_URL.trim()).into(moviePoster)

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

java.lang.NullPointerException in getting data to ListView in Android

Hie Friends
I have one ListView which displays image data from JSON parser for that I use Custom Base Adapter.
But I got following exception.
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.ecard.ECard_main$AsycLove.onPostExecute(ECard_main.java:193)
at com.example.ecard.ECard_main$AsycLove.onPostExecute(ECard_main.java:1)
at android.os.AsyncTask.finish(AsyncTask.java:602)
at android.os.AsyncTask.access$600(AsyncTask.java:156)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
My Code Is:
package com.example.ecard;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import com.loopj.android.image.SmartImageView;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ECard_main extends Activity
{
String catagories;
String anim_id,album_id,anim_name,anim_thumb,anim_url;
TextView title;
SmartImageView image;
ListView hlv;
ArrayList<HashMap<String, String>> albumList;
#Override
protected void onCreate(Bundle savedInstanceState)
{
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.ecard_main);
Intent i=getIntent();
catagories=i.getExtras().getString("Catagories");
title=(TextView)findViewById(R.id.tv_main_title);
image=(SmartImageView)findViewById(R.id.IV_image);
title.setText(catagories);
//hlv = getListView();
hlv = (ListView) findViewById(android.R.id.list);
albumList = new ArrayList<HashMap<String, String>>();
new AsycLove().execute();
}
class AsycLove extends AsyncTask<String, String, String>
{
ProgressDialog progressDialog;
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = new ProgressDialog(ECard_main.this);
progressDialog.setTitle("Loading");
progressDialog.setMessage("Please wait");
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(true);
progressDialog.show();
}
#Override
protected String doInBackground(String... aurl)
{
try
{
HttpPost postMethod = new HttpPost("http://demo1.idevtechnolabs.com/smartecard/love.php");
BufferedReader bufferedReader = null;
HttpClient client = new DefaultHttpClient();
HttpResponse response = null;
response = client.execute(postMethod);
final int statusCode = response.getStatusLine().getStatusCode();
Log.v("Album ::","Response:::--->"+response.toString());
Log.v("Album ::","Status Code:::--->"+statusCode);
bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer stringBuffer = new StringBuffer("");
String line = "";
String LineSeparator = System.getProperty("line.separator");
while ((line = bufferedReader.readLine()) != null)
{
stringBuffer.append(line + LineSeparator);
}
bufferedReader.close();
//-------------CONVERT DATA TO JSON---------------------------------
try
{
String myjsonstring = stringBuffer.toString();
JSONArray jsonArray = new JSONArray(myjsonstring);
JSONObject jsonObj = null;
albumList.clear();
jsonObj = jsonArray.getJSONObject(0);
for(int i=0; i<jsonArray.length();i++)
{
jsonObj = jsonArray.getJSONObject(i);
anim_id = jsonObj.getString("animation_id");
album_id = jsonObj.getString("album_id");
anim_name = jsonObj.getString("animation_name");
anim_thumb= jsonObj.getString("animation_thumb");
anim_url = jsonObj.getString("animation_url");
anim_url=anim_url.replaceAll("\"","");
Log.v("Anim URL","Anim URL::"+anim_url);
Log.v("Anim Name","Anim Name::"+anim_name);
HashMap<String, String> tmp_album = new HashMap<String, String>();
tmp_album.put("anim_id", anim_id);
tmp_album.put("anim_thumb", anim_thumb);
albumList.add(tmp_album);
}
}
catch (Exception e)
{
Log.v("Home ::","Call JSON Exception in get Album in List--->"+e.toString());
e.printStackTrace();
}
}
catch (IOException e)
{
Log.v("Exception: Get get Album in List","Name-"+e.toString());
e.printStackTrace();
}
return "0";
}
#Override
protected void onPostExecute(String code)
{
Toast.makeText(getApplicationContext(), "Image URL Call Successfully", Toast.LENGTH_LONG).show();
Log.v("Album","Album List::"+albumList);
ECard_main_Custom_Adapter adapter =new ECard_main_Custom_Adapter(getApplicationContext(),albumList);
hlv.setAdapter(adapter);
progressDialog.dismiss();
progressDialog = null;
}
}
}
And My Adapter Is:
import java.util.ArrayList;
import java.util.HashMap;
import com.loopj.android.image.SmartImageView;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
public class ECard_main_Custom_Adapter extends BaseAdapter
{
private Context context;
ArrayList<HashMap<String, String>> listAlbum;
ViewHolder vholder;
Drawable image;
public ECard_main_Custom_Adapter(Context context, ArrayList<HashMap<String, String>> albumList)
{
this.context = context;
this.listAlbum=albumList;
}
#Override
public int getCount()
{
Log.v("1","1");
return listAlbum.size();
}
#Override
public Object getItem(int position)
{
Log.v("1","2");
return position;
}
#Override
public long getItemId(int position)
{
Log.v("1","3");
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
Log.v("1","1");
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View vi=convertView;
vi = inflater.inflate(R.layout.ecard_main_adapter, null);
vholder = new ViewHolder();
vholder.img_album=(SmartImageView)vi.findViewById(R.id.IV_image);
vi.setTag(vholder);
try
{
String anim_id=listAlbum.get(position).get("anim_id");
String url=listAlbum.get(position).get("anim_thumb");
Log.v("Anim ID and Anim URL","Id:"+anim_id+" URL:"+url);
vholder.img_album.setImageUrl(url);
}
catch (Exception e)
{
// TODO: handle exception
Log.v("Error Ecard","Error is:::"+e);
}
return vi;
}
static class ViewHolder
{
SmartImageView img_album;
}
}
Please tell me where I am wrong.
Any help is appreciated.
Thanks In advance.
First correct this
hlv = (ListView) findViewById(android.R.id.list);
to
hlv = (ListView) findViewById(R.id.list);
It might cause an error. and make sure your ecard_main.xml layout contains ListView with id list

Android-Json parser not able to display data retrieved from back end

I am new to android. I am implementing a project in which I want to get the data from the back end and display on my android screen.
The Json I am trying to call is:-
[{"admin":null,"card_no":"8789","created_at":"2013-04-09T12:55:54Z","deleted":0,"email":"dfds#fgfd.com","entered_by":null,"first_name":"Gajanan","id":8,"last_name":"Bhat","last_updated_by":null,"middle_name":"","mobile":87981,"updated_at":"2013-04-13T05:26:25Z","user_type_id":null},{"admin":{"created_at":"2013-04-10T09:02:00Z","deleted":0,"designation":"Sr software Engineer","email":"admin#qwe.com","first_name":"Chiron","id":1,"last_name":"Synergies","middle_name":"Sr software Engineer","office_phone":"98789765","super_admin":false,"updated_at":"2013-04-10T12:03:04Z","username":"Admin"},"card_no":"66","created_at":"2013-04-08T09:47:15Z","deleted":0,"email":"rajaarun1991","entered_by":1,"first_name":"Arun","id":1,"last_name":"Raja\n","last_updated_by":1,"middle_name":"Nagaraj","mobile":941,"updated_at":"2013-04-08T09:47:15Z","user_type_id":1}]
My JsonParser.java is as follows:-
package com.example.library;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONArray jarray = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONArray getJSONFromUrl(String url) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e("==>", "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// try parse the string to a JSON object
try {
jarray = new JSONArray( builder.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jarray;
}
}
/* public void writeJSON() {
JSONObject object = new JSONObject();
try {
object.put("name", "");
object.put("score", new Integer(200));
object.put("current", new Double(152.32));
object.put("nickname", "Programmer");
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println(object);
}
*/
And my activity.java is as follows:-
package com.example.library;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class SecondActivity extends Activity
{
private Context context;
private static String url = "http://192.168.0.100:3000/users.json";
private static final String TAG_ID = "id";
private static final String TAG_FIRST_NAME = "first_name";
private static final String TAG_MIDDLE_NAME = "middle_name";
private static final String TAG_LAST_NAME = "last_name";
// private static final String TAG_POINTS = "experiencePoints";
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
ListView lv ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new ProgressTask(SecondActivity.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
public ProgressTask(SecondActivity secondActivity) {
Log.i("1", "Called");
context = secondActivity;
dialog = new ProgressDialog(context);
}
/** progress dialog to show user that the backup is processing. */
/** application context. */
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
ListAdapter adapter = new SimpleAdapter(context, jsonlist,
R.layout.list_item, new String[] { TAG_ID, TAG_FIRST_NAME,
TAG_MIDDLE_NAME, TAG_LAST_NAME }, new int[] {
R.id.id, R.id.first_name, R.id.middle_name,
R.id.last_name });
setListAdapter(adapter);
// selecting single ListView item
lv = getListView();
}
private void setListAdapter(ListAdapter adapter) {
// TODO Auto-generated method stub
}
protected Boolean doInBackground(final String... args) {
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url);
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
String id = c.getString(TAG_ID);
String first_name = c.getString(TAG_FIRST_NAME);
String middle_name = c.getString(TAG_MIDDLE_NAME);
String last_name = c.getString(TAG_LAST_NAME);
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_FIRST_NAME, first_name);
map.put(TAG_MIDDLE_NAME, middle_name);
map.put(TAG_LAST_NAME, last_name);
jsonlist.add(map);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
}
public ListView getListView() {
// TODO Auto-generated method stub
return null;
}
}
I am not able to show anything on the emulators for users,whereas I am able to fetch the data from the server
Actually in the project I want to display all the users present in the library.I am accessing the server which is on Ubuntu.
The following message is displayed on the console(Terminal):-
Started GET "/users.json" for 192.168.0.104 at 2013-05-05 22:05:01 -0700
Processing by UsersController#index as JSON
User Load (0.4ms) SELECT "users".* FROM "users" WHERE (users.deleted = 0) ORDER BY users.id DESC
Admin Load (0.3ms) SELECT "admins".* FROM "admins" WHERE "admins"."id" = 1 AND (admins.deleted = 0) ORDER BY admins.id DESC LIMIT 1
Completed 200 OK in 4ms (Views: 2.1ms | ActiveRecord: 0.6ms)
[2013-05-05 22:05:01] WARN Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true
However i am not able to display the data on the android screen/emulator.
Please help me with this.
I missed your setAdapterList()method.
Any error for your json pasers? and can you put your activity which is inherited from SecondActivity?
//modify getListView
public ListView getListView() {
// TODO Auto-generated method stub
listView = (ListView)findViewById(r.your.listview);
return listView;
}
//modify setListAdapter
private void setListAdapter(ListAdapter adapter) {
// TODO Auto-generated method stub
lv.setAdapter(adapter);
}

Categories

Resources