asynctask with callback - cant display images - java

Cannot display images.. unless putting the adding code in the callback function. But because i ve to cycle draw operation, ive just used the assignment
imageHandler = image; it seems to not work
activity class:
public class Home extends ActionBarActivity implements OnTaskComplete{
public Bitmap imageHandler;
#Override
public void callBackFunction(Bitmap image) {
imageHandler = image;
}
public class Post{
String id;
String title;
String description;
String release;
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public String getRelease() {
return release;
}
public void setTitle(String title) {
this.title = title;
}
public void setDescription(String description) {
this.description = description;
}
public void setRelease(String release) {
this.release = release;
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
}
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Context context = this;
String result = null;
ArrayList<Post> focusOn = new ArrayList<Post>();
try {
URL address = new URL("http://www.youth-stories.com/api/all.php");
URLDataReader reader = new URLDataReader(context);
result = reader.execute(address).get();
}catch (IOException e){
e.printStackTrace();
} catch(InterruptedException e){
e.printStackTrace();
} catch (ExecutionException e){
e.printStackTrace();
}
try {
JSONObject obj = new JSONObject(result);
String success = (String) obj.getString("success");
JSONArray records = obj.getJSONArray("records");
for(int i = 0; i < records.length(); i++) {
Post tmp = new Post();
tmp.setId(records.getJSONObject(i).getString("id"));
tmp.setTitle(records.getJSONObject(i).getString("title"));
tmp.setDescription(records.getJSONObject(i).getString("contents"));
tmp.setRelease(records.getJSONObject(i).getString("data_post"));
focusOn.add(tmp);
}
}catch (JSONException e){
e.printStackTrace();
}
//wrapper
LinearLayout container = (LinearLayout)findViewById(R.id.wrapper);
for(int i = 0; i < focusOn.size(); i++){
//item
LinearLayout item = new LinearLayout(getApplicationContext());
container.addView(item);
item.setOrientation(LinearLayout.HORIZONTAL);
//image
//Bitmap imageHandler = null;
URL address = null;
try {
address = new URL("http://www.youth-stories.com/public/admin/CH_FocusOn/images/"+focusOn.get(i).getId()+"_thumb2.jpg");
URLImageReader reader = new URLImageReader(context,this);
reader.execute(address);
}catch(MalformedURLException e){
e.printStackTrace();
}
ImageView asset = new ImageView(getApplicationContext());
asset.setImageBitmap(imageHandler);
//Toast.makeText(getApplicationContext(),asset.toString(),Toast.LENGTH_LONG).show();
item.addView(asset);
LinearLayout.LayoutParams imgSettings = new LinearLayout.LayoutParams(300,300);
asset.setLayoutParams(imgSettings);
//inside
LinearLayout contents = new LinearLayout(getApplicationContext());
contents.setOrientation(LinearLayout.VERTICAL);
item.addView(contents);
//title
TextView title = new TextView(getApplicationContext());
title.setText(focusOn.get(i).getTitle());
title.setTextAppearance(this, R.style.title);
contents.addView(title);
//description
TextView description = new TextView(getApplicationContext());
description.setText(focusOn.get(i).getDescription());
description.setTextAppearance(this, R.style.description);
contents.addView(description);
//date
TextView date = new TextView(getApplicationContext());
date.setText(focusOn.get(i).getRelease());
date.setTextAppearance(this, R.style.description);
contents.addView(date);
}
}
}
URLImageReader Asynctask
public class URLImageReader extends AsyncTask<URL, Void, Bitmap> {
Context context = null;
private OnTaskComplete mlistener;
public URLImageReader(Context context, OnTaskComplete mlistener){
this.context = context;
this.mlistener = mlistener;
}
#Override
protected Bitmap doInBackground(URL... params) {
Bitmap image = null;
try {
URL url= params[0];
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e){
e.printStackTrace();
}
return image;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
mlistener.callBackFunction(bitmap);
}
interface:
public interface OnTaskComplete{
void callBackFunction(Bitmap image);
}

You on task complete interface seems extraneous, just pass the imageview to it instead:
public class URLImageReader extends AsyncTask<URL, Void, Bitmap> {
private final Context context;
private final ImageView mImageView;
public URLImageReader(ImageView imageView){
this.context = imageView.getContext();
this.mImageView = imageView;
}
#Override
protected Bitmap doInBackground(URL... params) {
Bitmap image = null;
try {
URL url= params[0];
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e){
e.printStackTrace();
}
return image;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
if (mImageView != null){
mImageView.setImageBitmap(bitmap);
}
}
}
Then to call it,
// see final notes below about using this (the activity), lets create the imageview before we call URLImageReader constructor
ImageView asset = new ImageView(this);
try {
address = new URL("http://www.youth-stories.com/public/admin/CH_FocusOn/images/"+focusOn.get(i).getId()+"_thumb2.jpg");
URLImageReader reader = new URLImageReader(asset);
reader.execute(address);
}catch(MalformedURLException e){
e.printStackTrace();
}
Also, don't use the application context to create views, use the Activity context instead.

Related

RecyclerView: No adapter attached; skipping layout when Im running

I'm new coder of android and trying to get list of images in my server and database(mysql) but I got error and I don't know what is causing it...
the error is 'E/RecyclerView: No adapter attached; skipping layout' and it happen when I'm running, anyone can help me??
public class LoadListFromServer extends AsyncTask<String, Void, String> {
private RecyclerView recyclerView;
private Context context;
private ArrayList<ImageGalleryItem> imageGalleryItems;
private boolean pattern;
public LoadListFromServer(RecyclerView recyclerView, Context context, boolean pattern) {
this.recyclerView = recyclerView;
this.context = context;
this.pattern = pattern;
}
public ArrayList<ImageGalleryItem> getImageGalleryItems() {
return imageGalleryItems;
}
#Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Content-type", "application/json");
int responseCode = urlConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
return readStream(urlConnection.getInputStream());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(context,2);
recyclerView.setLayoutManager(layoutManager);
imageGalleryItems = prepareData(response);
MyAdapter adapter = new MyAdapter(context, imageGalleryItems);
recyclerView.setAdapter(adapter);
}
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in, "UTF-8"), 8);
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}
private ArrayList<ImageGalleryItem> prepareData(String response) {
ArrayList<ImageGalleryItem> result = null;
try {
JSONArray jsonArray = new JSONArray(response);
result = new ArrayList<>(jsonArray.length());
for (int i=0; i < jsonArray.length(); i++) {
try {
JSONObject oneObject = jsonArray.getJSONObject(i);
String id = oneObject.getString("id");
String name = oneObject.getString("name");
result.add(new ImageGalleryItem(name, Long.parseLong(id), pattern));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
if(result == null) {
return new ArrayList<>();
} else {
return result;
}
}
}
I wrote my adapter as MyAdapter.java:
class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private ArrayList<ImageGalleryItem> galleryList;
public MyAdapter(Context context, ArrayList<ImageGalleryItem> galleryList) {
this.galleryList = galleryList;
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cell_layout, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(MyAdapter.ViewHolder viewHolder, int i) {
final ImageGalleryItem imageGalleryItem = galleryList.get(i);
viewHolder.title.setText(imageGalleryItem.getName());
viewHolder.img.setScaleType(ImageView.ScaleType.FIT_XY);
String imageFolderName;
final boolean isPattern = imageGalleryItem.isPattern();
if(isPattern) {
imageFolderName = viewHolder.img.getContext().getString(R.string.patterns_directory);
} else {
imageFolderName = viewHolder.img.getContext().getString(R.string.collections_directory);
}
LoadSVGFromServer loadSVGFromServer = new LoadSVGFromServer(viewHolder.img);
loadSVGFromServer.execute(viewHolder.img.getContext().getString(R.string.server_base_address)
+ imageFolderName
+ imageGalleryItem.getID() + ".svg");
viewHolder.img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Activity activity = (Activity) v.getContext();
if(isPattern) {
Intent intent = new Intent(activity, ColoringActivity.class);
Bundle b = new Bundle();
b.putSerializable(activity.getString(R.string.CURRENT_COLLECTION_BUNDLE_KEY), imageGalleryItem);
intent.putExtras(b);
activity.startActivity(intent);
} else {
Intent intent = new Intent(activity, ShowPatternsActivity.class);
Bundle b = new Bundle();
b.putSerializable(activity.getString(R.string.CURRENT_COLLECTION_BUNDLE_KEY), imageGalleryItem);
intent.putExtras(b);
activity.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return galleryList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView title;
private ImageView img;
public ViewHolder(View view) {
super(view);
title = (TextView)view.findViewById(R.id.title);
img = (ImageView) view.findViewById(R.id.img);
}
}
}
You can setup your recyclerView and set items when data received.
activity code for setup recycler view:
public class MainActivity extends AppCompatActivity {
private MyAdapter mAdapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupRecyclerView();
}
private void setupRecyclerView(){
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(context,2);
recyclerView.setLayoutManager(layoutManager);
mAdapter = new MyAdapter(context);
recyclerView.setAdapter(mAdapter);
}
}
Pass adapter to async task:
public class LoadListFromServer extends AsyncTask<String, Void, String> {
private MyAdapter mAdapter;
private Context context;
private ArrayList<ImageGalleryItem> imageGalleryItems;
private boolean pattern;
public LoadListFromServer(MyAdapter adapter, Context context, boolean pattern) {
this.mAdapter = adapter;
this.context = context;
this.pattern = pattern;
}
public ArrayList<ImageGalleryItem> getImageGalleryItems() {
return imageGalleryItems;
}
#Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Content-type", "application/json");
int responseCode = urlConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
return readStream(urlConnection.getInputStream());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
imageGalleryItems = prepareData(response);
mAdapter.setItems(imageGalleryItems);
}
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in, "UTF-8"), 8);
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}
private ArrayList<ImageGalleryItem> prepareData(String response) {
ArrayList<ImageGalleryItem> result = null;
try {
JSONArray jsonArray = new JSONArray(response);
result = new ArrayList<>(jsonArray.length());
for (int i=0; i < jsonArray.length(); i++) {
try {
JSONObject oneObject = jsonArray.getJSONObject(i);
String id = oneObject.getString("id");
String name = oneObject.getString("name");
result.add(new ImageGalleryItem(name, Long.parseLong(id), pattern));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
if(result == null) {
return new ArrayList<>();
} else {
return result;
}
}
}
Adapter with setItems method:
class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private ArrayList<ImageGalleryItem> galleryList;
public MyAdapter(Context context) {
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cell_layout, viewGroup, false);
return new ViewHolder(view);
}
public void setItems(ArrayList<ImageGalleryItem> galleryList){
this.galleryList = galleryList;
notifyDataSetChanged();
}
#Override
public void onBindViewHolder(MyAdapter.ViewHolder viewHolder, int i) {
final ImageGalleryItem imageGalleryItem = galleryList.get(i);
viewHolder.title.setText(imageGalleryItem.getName());
viewHolder.img.setScaleType(ImageView.ScaleType.FIT_XY);
String imageFolderName;
final boolean isPattern = imageGalleryItem.isPattern();
if(isPattern) {
imageFolderName = viewHolder.img.getContext().getString(R.string.patterns_directory);
} else {
imageFolderName = viewHolder.img.getContext().getString(R.string.collections_directory);
}
LoadSVGFromServer loadSVGFromServer = new LoadSVGFromServer(viewHolder.img);
loadSVGFromServer.execute(viewHolder.img.getContext().getString(R.string.server_base_address)
+ imageFolderName
+ imageGalleryItem.getID() + ".svg");
viewHolder.img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Activity activity = (Activity) v.getContext();
if(isPattern) {
Intent intent = new Intent(activity, ColoringActivity.class);
Bundle b = new Bundle();
b.putSerializable(activity.getString(R.string.CURRENT_COLLECTION_BUNDLE_KEY), imageGalleryItem);
intent.putExtras(b);
activity.startActivity(intent);
} else {
Intent intent = new Intent(activity, ShowPatternsActivity.class);
Bundle b = new Bundle();
b.putSerializable(activity.getString(R.string.CURRENT_COLLECTION_BUNDLE_KEY), imageGalleryItem);
intent.putExtras(b);
activity.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return galleryList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView title;
private ImageView img;
public ViewHolder(View view) {
super(view);
title = (TextView)view.findViewById(R.id.title);
img = (ImageView) view.findViewById(R.id.img);
}
}
}

loading images to a recyclerview using a thread

So I have a Recyclerview which holding items with images, I want to load images into the items but when I do that I got a lot of fps drops.
I read that I need to use another thread for the network part and I tried to do that as you can see, and it seems good to me but I can't figure out how to stop the fps drops and make the scrolling in the Recyclerview smooth, this Recyclerview supposed to hold between 10 and 100. Am I supposed to run the activity in a thread?
Note: The fps drops occur with 10 items.
calling to the HttpWrapper.LoadImageFromWebOperations function in OnBindViewHolder.
HomeAdapter.java
public class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.HomeViewHolder>{
private Context context;
private ArrayList<RecipeModel> items;
public HomeAdapter(Context context, ArrayList<RecipeModel> items) {
this.context = context;
this.items = items;
}
#Override
public HomeAdapter.HomeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.home_item,null);
HomeAdapter.HomeViewHolder holder = new HomeAdapter.HomeViewHolder(v);
return holder;
}
public void addItem(RecipeModel item){
this.items.add(item);
notifyDataSetChanged();
}
#Override
public void onBindViewHolder(HomeAdapter.HomeViewHolder holder, final int position) {
RecipeModel model = items.get(position);
holder.name.setText(model.getName());
holder.directions.setText(model.getDirections()[0]);
Drawable drawable = HttpWrapper.LoadImageFromWebOperations(model.getImageSource());
holder.image.setImageDrawable(drawable);
}
#Override
public int getItemCount() {
return items.size();
}
class HomeViewHolder extends RecyclerView.ViewHolder{
TextView name;
TextView directions;
ImageView image;
public HomeViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.recipe_name);
directions = (TextView) itemView.findViewById(R.id.recipe_directions);
image = (ImageView) itemView.findViewById(R.id.recipe_image);
}
}
HttpWrapper.java
public class HttpWrapper {
String responseMsg = "";
private OkHttpClient client;
private Request request;
public static final String base_url = "http://kingtimmy.pythonanywhere.com";
public static final String home_route = "/home/";
public HttpWrapper() {
client = new OkHttpClient();
}
public ArrayList<RecipeModel> get_home_recipes(int recipe_num){
ArrayList<RecipeModel> models = new ArrayList<RecipeModel>();
request = new Request.Builder().url(base_url + home_route + String.valueOf(recipe_num)).build();
responseMsg = "";
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
responseMsg = "Error: " + e.getMessage();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
responseMsg = response.body().string();
}
});
while(responseMsg.equals("")){
continue;
}
String[] jsons = responseMsg.split("]-]");
for (int i = 0; i < jsons.length; i++){
models.add(makeRecipeModel(jsons[i]));
}
return models;
}
public RecipeModel makeRecipeModel(String msg){
JSONObject nodeRoot = null;
RecipeModel model;
try {
nodeRoot = new JSONObject(msg);
String[] directions = nodeRoot.get("directions").toString().split("\\n");
String[] ingredients = nodeRoot.get("ingredients").toString().split("\\n");
String image_source = nodeRoot.get("image").toString();
String source_url = nodeRoot.get("source_url").toString();
String name = nodeRoot.get("name").toString();
int id = Integer.valueOf(nodeRoot.get("id").toString());
model = new RecipeModel(directions,ingredients,image_source,source_url,name,id);
} catch (JSONException e) {
model = null;
}
return model;
}
public static Drawable LoadImageFromWebOperations(final String url) {
ExecutorService executor = Executors.newSingleThreadExecutor();
Callable<Drawable> callable = new Callable<Drawable>() {
#Override
public Drawable call() {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
System.out.println("Exc=" + e);
return null;
}
}
};
Future<Drawable> future = executor.submit(callable);
// future.get() returns 2 or raises an exception if the thread dies, so safer
try {
Drawable d = future.get();
executor.shutdown();
return d;
} catch (Exception e) {
return null;
}
}
What am I doing wrong?
Instead of writing your own thread and code to fetch, parse, decode and load the image, give Glide a try. It does all that for you with a simple single line code and loads the image in your ImageView

How to get a single column in android mysql

How can i get a single column using using android. instead of getting everything from the database. i want to get only the column where full_name="john".
DataParser.jave
public class DataParser extends AsyncTask<Void,Void,Integer>{
Context c;
ListView lv;
String jsonData;
ProgressDialog pd;
ArrayList<Person> persons=new ArrayList<>();
public DataParser(Context c, ListView lv, String jsonData) {
this.c = c;
this.lv = lv;
this.jsonData = jsonData;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd=new ProgressDialog(c);
pd.setTitle("Parse");
pd.setMessage("Parsing...Please wait");
pd.show();
}
#Override
protected Integer doInBackground(Void... params) {
return this.parseData();
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
pd.dismiss();
if(result==0)
{
Toast.makeText(c,"Unable to parse",Toast.LENGTH_SHORT).show();
}else {
//CALL ADAPTER TO BIND DATA
CustomAdapter adapter=new CustomAdapter(c,persons);
lv.setAdapter(adapter);
}
}
private int parseData()
{
try {
JSONArray ja=new JSONArray(jsonData);
JSONObject jo=null;
persons.clear();
Person s=null;
for(int i=0;i<ja.length();i++) {
jo = ja.getJSONObject(i);
int id = jo.getInt("id");
String name = jo.getString("full_name");
String sex = jo.getString("sex");
String location = jo.getString("location");
s = new Person();
s.setId(id);
s.setFull_name(name);
s.setSex(sex);
s.setLocation(location);
persons.add(s);
}
return 1;
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
}
Downloader.java
public class Downloader extends AsyncTask<Void,Void,String> {
Context c;
String urlAddress;
ListView lv;
ProgressDialog pd;
public Downloader(Context c, String urlAddress, ListView lv) {
this.c = c;
this.urlAddress = urlAddress;
this.lv = lv;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd=new ProgressDialog(c);
pd.setTitle("Fetch");
pd.setMessage("Fetching....Please wait");
pd.show();
}
#Override
protected String doInBackground(Void... params) {
return this.downloadData();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
pd.dismiss();
if(s==null)
{
Toast.makeText(c,"Unsuccessfull,Null
returned",Toast.LENGTH_SHORT).show();
}else
{
//CALL DATA PARSER TO PARSE
DataParser parser=new DataParser(c,lv,s);
parser.execute();
}
}
private String downloadData()
{
HttpURLConnection con=Connector.connect(urlAddress);
if(con==null)
{
return null;
}
InputStream is=null;
try {
is=new BufferedInputStream(con.getInputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String line=null;
StringBuffer response=new StringBuffer();
if(br != null)
{
while ((line=br.readLine()) != null)
{
response.append(line+"\n");
}
br.close();
}else
{
return null;
}
return response.toString();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(is != null)
{
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}
Connector.java
public class Connector {
public static HttpURLConnection connect(String urlAddress)
{
try {
URL url=new URL(urlAddress);
HttpURLConnection con= (HttpURLConnection) url.openConnection();
//SET PROPS
con.setRequestMethod("GET");
con.setConnectTimeout(20000);
con.setReadTimeout(20000);
con.setDoInput(true);
return con;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Person.java
public class Person {
int id;
String full_name, sex, location;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFull_name() {
return full_name;
}
public void setFull_name(String full_name) {
this.full_name = full_name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
CustomAdapter.java
public class CustomAdapter extends BaseAdapter {
Context c;
ArrayList<Person> persons;
LayoutInflater inflater;
public CustomAdapter(Context c, ArrayList<Person> persons) {
this.c = c;
this.persons = persons;
//INITIALIE
inflater= (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return persons.size();
}
#Override
public Object getItem(int position) {
return persons.get(position);
}
#Override
public long getItemId(int position) {
return persons.get(position).getId();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if(convertView==null)
{
convertView=inflater.inflate(R.layout.model,parent,false);
}
TextView nameTxt= (TextView) convertView.findViewById(R.id.nameTxt);
TextView sexTxt= (TextView) convertView.findViewById(R.id.propellantTxt);
TextView locationTxt= (TextView) convertView.findViewById(R.id.descTxt);
nameTxt.setText(persons.get(position).getFull_name());
sexTxt.setText(persons.get(position).getSex());
locationTxt.setText(persons.get(position).getLocation());
//ITEM CLICKS
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(c,persons.get(position).getFull_name(),Toast.LENGTH_SHORT).show();
}
});
return convertView;
}
}
server side php file
<?php
$host = 'localhost';
$username='root';
$pwd ='';
$db ='user';
$con=mysqli_connect($host,$username,$pwd,$db) or die('Unable to connect');
if(mysqli_connect_error($con))
{
echo "Failed to Connect to Database ".mysqli_connect_error();
}
$query=mysqli_query($con,"SELECT * FROM person");
if($query)
{
while($row=mysqli_fetch_array($query))
{
$data[]=$row;
}
print(json_encode($data));
}else
{
echo('Not Found ');
}
mysqli_close($con);
?>
mainactivity.java
public class MainActivity extends AppCompatActivity {
String urlAddress="http://localhost/Android/includes/retrive.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ListView lv= (ListView) findViewById(R.id.lv);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Downloader d=new Downloader(MainActivity.this,urlAddress,lv);
d.execute();
}
});
}
}
Got the code online and cant find a way to get a single column
It looks like the json you are using is from an API response. In that case, if you want to do it in SQL you would need to create a new api and SQL query on the server. If you want to just limit what is displaying in the loop, only parse the parts you want.
for(int i=0;i<ja.length();i++) {
jo = ja.getJSONObject(i);
int id = jo.getInt("id");
String name = jo.getString("full_name");
s = new Person();
s.setFull_name(name);
persons.add(s);
}
You would then need to also change the logic in your activity that displays the data, and only display person.name, as the rest of the properties will be null.
I recommend doing more research on consuming APIs and parsing JSON, as it appears that the code you are using does not have a database or SQL.

how to fetch data without button click

how to fetch first image without click fetch image button
click to view image
this code work fine but on click fetch image button but i want fetch image with out click fetch images button i want to remove this button
Public class MainActivity extends AppCompatActivity implements
View.OnClickListener {
private String imagesJSON;
private static final String JSON_ARRAY ="result";
private static final String IMAGE_URL = "url";
private JSONArray arrayImages= null;
private int TRACK = 0;
private static final String IMAGES_URL = "http://www.simplifiedcoding.16mb.com/ImageUpload/getAllImages.php";
private Button buttonFetchImages;
private Button buttonMoveNext;
private Button buttonMovePrevious;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
buttonFetchImages = (Button) findViewById(R.id.buttonFetchImages);
buttonMoveNext = (Button) findViewById(R.id.buttonNext);
buttonMovePrevious = (Button) findViewById(R.id.buttonPrev);
buttonFetchImages.setOnClickListener(this);
buttonMoveNext.setOnClickListener(this);
buttonMovePrevious.setOnClickListener(this);
}
private void extractJSON(){
try {
JSONObject jsonObject = new JSONObject(imagesJSON);
arrayImages = jsonObject.getJSONArray(JSON_ARRAY);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void showImage(){
try {
JSONObject jsonObject = arrayImages.getJSONObject(TRACK);
getImage(jsonObject.getString(IMAGE_URL));
} catch (JSONException e) {
e.printStackTrace();
}
}
private void moveNext(){
if(TRACK < arrayImages.length()){
TRACK++;
showImage();
}
}
private void movePrevious(){
if(TRACK>0){
TRACK--;
showImage();
}
}
private void getAllImages() {
class GetAllImages extends AsyncTask<String,Void,String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Fetching Data...","Please Wait...",true,true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
imagesJSON = s;
extractJSON();
showImage();
}
#Override
protected String doInBackground(String... params) {
String uri = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while((json = bufferedReader.readLine())!= null){
sb.append(json+"\n");
}
return sb.toString().trim();
}catch(Exception e){
return null;
}
}
}
GetAllImages gai = new GetAllImages();
gai.execute(IMAGES_URL);
}
private void getImage(String urlToImage){
class GetImage extends AsyncTask<String,Void,Bitmap>{
ProgressDialog loading;
#Override
protected Bitmap doInBackground(String... params) {
URL url = null;
Bitmap image = null;
String urlToImage = params[0];
try {
url = new URL(urlToImage);
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this,"Downloading Image...","Please wait...",true,true);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
loading.dismiss();
imageView.setImageBitmap(bitmap);
}
}
GetImage gi = new GetImage();
gi.execute(urlToImage);
}
#Override
public void onClick(View v) {
if(v == buttonFetchImages) {
getAllImages();
}
if(v == buttonMoveNext){
moveNext();
}
if(v== buttonMovePrevious){
movePrevious();
}
}
}
You can trigger it in onCreate(),but you must not run it on UI thread,for it might be a time-consuming operation.Read Specifying the Code to Run on a Thread to help,
you might add the following block in your onCreate() method:
new Runnable() {
#Override
public void run() {
getAllImages();
}
}.run();

Mapping JSON data to Java POJO Class with Jackson Mapper, want to get result in listview

Trying to parse using jackson through intent data and adding to pojo class and getting back but not able to send and fetch ?
MainActivity is..
public class MainActivity extends AppCompatActivity {
private Button getButton;
private TextView textView;
private String jsonData;
#Override
protected void onCreate(Bundle savedInstanceState)
{
setContentView(R.layout.activity_json);
super.onCreate(savedInstanceState);
getButton = (Button) findViewById(R.id.getButton);
textView = (TextView) findViewById(R.id.textView);
getButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
new JSONTask().execute("http://192.168.11.75/Headspire/api.php");
}
});
}
public class JSONTask extends AsyncTask<String, String, String>
{
private String json_string = "";
#Override
protected String doInBackground(String... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
InputStream stream = urlConnection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
while ((json_string = reader.readLine()) != null) {
buffer.append(json_string);
}
return buffer.toString();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(final String result) {
super.onPostExecute(result);
textView.setText(result);
jsonData = result;
}
}
public void parseJSON(View view)
{
if (jsonData == null)
{
Toast.makeText(getApplicationContext(),
"Get JSON data first", Toast.LENGTH_SHORT).show();
}
else
{
Intent intent = new Intent(this, ActivityListView.class);
intent.putExtra("json_data", jsonData);
startActivity(intent);
}
}
}
Here this is my ActivityListView class...
public class ActivityListView extends AppCompatActivity
{
private String jsonData;
private ListView listView;
private PersonAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_list_view);
listView = (ListView) findViewById(R.id.listView);
adapter = new PersonAdapter(this, R.layout.row);
listView.setAdapter(adapter);
jsonData = getIntent().getExtras().getString("json_data");
ObjectMapper mapper = new ObjectMapper();
try
{
PersonModel model = mapper.readValue(jsonData, PersonModel.class);
model.getName();
model.getId();
model.getDescription();
model.getRating();
adapter.add(model);
}
catch (JsonParseException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
My PersonAdapeter class looks like this
public class PersonAdapter extends ArrayAdapter
{
private List list = new ArrayList();
public PersonAdapter(Context context, int resource) {
super(context, resource);
}
#SuppressWarnings("unchecked")
public void add(PersonModel object)
{
super.add(object);
list.add(object);
}
#Override
public int getCount()
{
return list.size();
}
#Override
public Object getItem(int position)
{
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View row;
row = convertView;
NameHolder nameHolder;
if (row == null)
{
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.row, parent, false);
nameHolder = new NameHolder();
nameHolder.nameTextView = (TextView) row.findViewById(R.id.nameTextView);
nameHolder.idTextView = (TextView) row.findViewById(R.id.idTextView);
nameHolder.descriptionTextView = (TextView) row.findViewById(R.id.descriptionTextView);
nameHolder.ratingTextView = (TextView) row.findViewById(R.id.ratingTextView);
row.setTag(nameHolder);
}
else {
nameHolder = (NameHolder)row.getTag();
}
PersonModel model = (PersonModel) this.getItem(position);
nameHolder.nameTextView.setText(model.getName());
nameHolder.idTextView.setText(model.getId());
nameHolder.descriptionTextView.setText(model.getDescription());
nameHolder.ratingTextView.setText(model.getRating());
return row;
}
static class NameHolder
{
TextView nameTextView, idTextView, descriptionTextView, ratingTextView;
}
}
Here it is my PersonModel class...
#JsonIgnoreProperties(ignoreUnknown=true)
public class PersonModel extends AppCompatActivity
{
private String name;
private String id;
private String description;
private String rating;
public PersonModel(String name, String id, String description,
String rating)
{
this.name = name;
this.id = id;
this.description = description;
this.rating = rating;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
#Override
public String toString()
{
return "PersonModel [name=" + name + ", id=" + id + ",
description=" + description + ", " +
"rating=" + rating +"]";
}
}

Categories