How To Set Image Resource To Android ImageView from Rest API - android

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.*******.******.app.R;
import com.*******.******.app.adapter.CustomAdapter;
import com.*******.******.app.adapter.CustomPromoAdapter;
import com.*******.******.app.pojo.Campaigns;
import com.*******.******.app.pojo.ConsumerProfile;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
public class Promo extends AppCompatActivity {
private ArrayList<String> imageurls = new ArrayList<>();
private ArrayList<String> imgnames = new ArrayList<>();
GridView gridview;
Context context;
ArrayList programName;
String campid,campImage,campName;
TextView name;
ImageView images;
// public static String[] programNameList = {"AppleMacBook", "HP_note_Book", "LG_NEXUS", "NokiaLumia", "SamsungRT", "SONY_BRAVIA", "Sansui"};
// public static int[] programImages = {R.drawable.apple, R.drawable.hp, R.drawable.nexus, R.drawable.lumia, R.drawable.fridge, R.drawable.tv, R.drawable.tv1};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_promo);
new HttpRequesrPromo().execute();
new HttpLocationPromo().execute();
gridview = (GridView) findViewById(R.id.gridView1);
//gv.setAdapter(new CustomPromoAdapter(this,programNameList,programImages));
CustomPromoAdapter adapter = new CustomPromoAdapter(this,imageurls,imgnames);
gridview.setAdapter(adapter);
name = (TextView) findViewById(R.id.textView1);
images = (ImageView) findViewById(R.id.imageView1);
}
private class HttpRequesrPromo extends AsyncTask<Void, Void, Campaigns> {
#Override
protected Campaigns doInBackground(Void... params) {
try {
final String url = "http://myurl";
RestTemplate restTemplate = new RestTemplate();
Campaigns campa = restTemplate.getForObject(url, Campaigns.class);
return campa;
} catch (Exception e) {
Log.e("MainActivity", e.getMessage(), e);
}
return null;
}
#Override
protected void onPostExecute(Campaigns campa) {
super.onPostExecute(campa);
campid = campa.getId();
Log.d("Campaign Idddddd~~~~~~~~", "onPostExecute: " + campid);
}
}
private class HttpLocationPromo extends AsyncTask<Void, Void, Campaigns> {
#Override
protected Campaigns doInBackground(Void... params) {
try {
final String url = "http://myurl";
RestTemplate restTemplate = new RestTemplate();
Campaigns locationcampa = restTemplate.getForObject(url, Campaigns.class);
return locationcampa;
} catch (Exception e) {
Log.e("MainActivity", e.getMessage(), e);
}
return null;
}
#Override
protected void onPostExecute(Campaigns locationcampa) {
super.onPostExecute(locationcampa);
campImage=locationcampa.getImage();
campName=locationcampa.getName();
imgnames.add(campName);
name.setText(campName);
Log.d("ImageUUURRRLLL", "onPostExecute: " + campImage);
Log.d("CampNNNAAMMEEE", "onPostExecute: " +campName);
imageurls.add(campImage);
}
}
}
This is my Activity Here I'm Getting Images From Rest Service and adding them in a list.
I have a GridView With CustomAdapter ImageView And TextView I want to set the Image Resource To Image View.
Below is My Adapter.......
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.app.R;
import com.app.activity.MainActivity;
import com.app.activity.Promo;
import java.util.ArrayList;
/**
* Created by ns2 on 2/4/16.
*/
public class CustomPromoAdapter extends BaseAdapter{
ImageView imageView;
TextView textView;
String [] result;
Context context;
int [] imageId;
private static LayoutInflater inflater=null;
public CustomPromoAdapter(Promo promo, ArrayList<String> imageurls, ArrayList<String> imgnames) {
// TODO Auto-generated constructor stub
//result=programNameList;
// context=promo;
// imageId=programImages;
inflater = ( LayoutInflater )context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return result.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view;
view=inflater.inflate(R.layout.promo_gridlist,null);
/* textView=(TextView)view.findViewById(R.id.textView1);
imageView=(ImageView)view.findViewById(R.id.imageView1);
imageView.setImageResource(imageId[position]);
textView.setText(imageId[position]);*/
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "You Clicked " + result[position], Toast.LENGTH_LONG).show();
}
});
return view;
}
}
This is my Adapter.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_gravity="center"
android:layout_width="88dp"
android:layout_height="88dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
/>
<TextView
android:id="#+id/textView1"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:text="TextView" />
</LinearLayout>
This is my Layout with ImageView And TextView.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".activity.Promo" >
<GridView
android:id="#+id/gridView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:numColumns="2" >
</GridView>
</RelativeLayout>
This is my Main layout.
I Have The Image Url's In a List now I want to Set those Url's to ImageView.
I'm new To Android Can Any One Help Me How To Solve This Problem.
Thankful To Them........

Best way to load images from server is
Glide.with(mContext)
.load(imageUrl)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.placeholder(R.drawable.default)
.error(R.drawable.default)
.override(400, 400)
.centerCrop()
.into(imageView);
For more follow this :
https://github.com/bumptech/glide

Best way to achieve this is use picasso library.
Picasso.with(context)
.load(url)
.placeholder(R.drawable.user_placeholder)
.error(R.drawable.user_placeholder_error)
.into(imageView);
for more details

Try this,
URL photoUrl = new URL(imageUrl);
mIcon = BitmapFactory.decodeStream(photoUrl.openConnection() .getInputStream());
imageView.setImageBitmap(mIcon);

Related

Custom Adapter not working for RecyclerView in a Fragment

I am working on an Android Project to display Github repo details.
I am trying to first select org name for a particular company, like Amazon has orgs on Github like AWS, AMZN, AWSLABS etc.
For this I first create a List of clickable buttons via RecyclerView(which works).
Then when user clicks on a particular org_name, the App does a HTTP request to Github to fetch relevant info and display inside a fragment which uses another RecyclerView(not working RecyclerViewRepoAdapter.java).
This part does not work as onCreateViewHolder or onBindViewHolder is not called (getItemCount is called and returns correct length)
Tried some of the suggestions mentioned like in this link! but it didn't work.
Any help is appreciated!
OrganizationInfo.java // Driver program
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class OrganizationInfo extends AppCompatActivity {
private String companyName;
private String companyAddress;
private List<String> orgNames;
private TextView companyNameTV;
private TextView companyAddressTV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_organization_info);
getCompanyData();
companyNameTV = findViewById(R.id.companyNameTv);
companyAddressTV = findViewById(R.id.companyAddressTv);
companyNameTV.setText(companyName);
companyAddressTV.setText(companyAddress);
initRecyclerView();
}
private void getCompanyData() {
companyName = "amazon";
companyAddress = "207 Boren Ave N, Seattle, WA 98109";
orgNames = new ArrayList<>();
orgNames.add("amzn");
orgNames.add("aws");
orgNames.add("awslabs");
}
private void initRecyclerView(){
// Log.d(TAG, "initRecyclerView: init recyclerview");
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
RecyclerView recyclerView = findViewById(R.id.orgListRecyclerView);
recyclerView.setLayoutManager(layoutManager);
RecyclerViewOrgAdapter adapter = new RecyclerViewOrgAdapter(this, orgNames);
recyclerView.setAdapter(adapter);
}
}
GithubFragment.java
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A simple {#link Fragment} subclass.
*/
public class GithubFragment extends Fragment {
private List<Repository> repositories = new ArrayList<>();
RecyclerView recyclerView;
RecyclerViewRepoAdapter listAdapter;
public GithubFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
assert getArguments() != null;
View v = inflater.inflate(R.layout.fragment_github, container, false);
recyclerView = v.findViewById(R.id.repo_recycler_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
listAdapter = new RecyclerViewRepoAdapter(getContext(), repositories); // List of Github repos to be display
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(listAdapter); // Called from here after response from cloud funtion
return v;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
if (getArguments() != null) {
String orgName = getArguments().getString("org_name");
GraphQLAsyncTask graphQLAsyncTask = new GraphQLAsyncTask();
graphQLAsyncTask.execute(orgName, "");
}
}
private class GraphQLAsyncTask extends AsyncTask<String, String, String> {
private String response;
private Reader in;
#Override
protected String doInBackground(String... body) {
Map<String, String> params = new HashMap<>();
params.put("company", body[0]);
params.put("language", body[1]);
StringBuilder postData = new StringBuilder();
try{
for (Map.Entry param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey().toString(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
String url = "https://****************/getOrgReposGraphQL";
URL urlObj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.getOutputStream().write(postDataBytes);
conn.connect();
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
StringBuilder sb = new StringBuilder();
for (int c; (c = in.read()) >= 0; )
sb.append((char) c);
response = sb.toString();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String response) {
ParseResponse parseResponse = new ParseResponse(response);
repositories.addAll(parseResponse.getRepositories());
listAdapter.notifyDataSetChanged();
}
}
}
RecyclerViewRepoAdapter.java // Problematic Adapter
package edu.neu.madcourse.goexplore;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class RecyclerViewRepoAdapter extends RecyclerView.Adapter<RecyclerViewRepoAdapter.ListViewHolder> {
private List<Repository> mRepositories;
private Context mContext;
private int mCounter = 1;
public RecyclerViewRepoAdapter(Context context, List<Repository> repos) {
mRepositories = repos;
mContext = context;
}
#NonNull
#Override
public ListViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_repo, parent, false);
return new ListViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ListViewHolder holder, int position) {
Repository repo = mRepositories.get(position);
holder.repoTV.setText(repo.getNameWithOwner());
holder.repoLangugeTV.setText(repo.getPrimaryLanguage());
holder.repoStarsTV.setText(repo.getStargazers());
holder.repoCounter.setText(String.valueOf(mCounter++) + ".");
}
#Override
public int getItemCount() {
return mRepositories.size();
}
public class ListViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView repoTV;
TextView repoLangugeTV;
TextView repoStarsTV;
TextView repoCounter;
public ListViewHolder(View itemView) {
super(itemView);
repoTV = itemView.findViewById(R.id.repo_name_row);
repoLangugeTV = itemView.findViewById(R.id.repo_language_tv);
repoStarsTV = itemView.findViewById(R.id.repo_stars_tv);
repoCounter = itemView.findViewById(R.id.repo_list_number);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
}
}
}
RecyclerViewOrgAdapter.java
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class RecyclerViewOrgAdapter extends RecyclerView.Adapter<RecyclerViewOrgAdapter.ViewHolder> {
private static final String TAG = "RecyclerViewOrgAdapter";
private List<String> orgs;
private Context context;
public RecyclerViewOrgAdapter(Context context, List<String> orgs) {
this.orgs = orgs;
this.context = context;
}
#NonNull
#Override
public RecyclerViewOrgAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.organization_id_relative_layout, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final RecyclerViewOrgAdapter.ViewHolder holder, final int position) {
holder.orgIdBtn.setText(orgs.get(position));
holder.orgIdBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AppCompatActivity activity = (AppCompatActivity) v.getContext();
Fragment githubFragment = new GithubFragment();
Bundle bundle = new Bundle();
bundle.putString("org_name", orgs.get(position));
githubFragment.setArguments(bundle);
activity.getSupportFragmentManager().beginTransaction().replace(R.id.github_fragment, githubFragment).addToBackStack(null).commit();
}
});
}
#Override
public int getItemCount() {
return orgs.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
Button orgIdBtn;
public ViewHolder(View itemView) {
super(itemView);
orgIdBtn = itemView.findViewById(R.id.orgIdBtn);
}
}
}
list_item_repo.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/repo_list_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:text="1."
android:textSize="24sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/repo_name_row"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:layout_marginTop="16dp"
android:text="Repo Name"
android:textSize="24sp"
app:layout_constraintStart_toEndOf="#+id/repo_list_number"
app:layout_constraintTop_toTopOf="parent" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="#+id/imageView2"
android:layout_width="42dp"
android:layout_height="33dp"
android:layout_marginTop="12dp"
app:layout_constraintStart_toStartOf="#+id/repo_name_row"
app:layout_constraintTop_toBottomOf="#+id/repo_name_row"
app:srcCompat="#mipmap/star_dark_round" />
<TextView
android:id="#+id/repo_stars_tv"
android:layout_width="42dp"
android:layout_height="33dp"
android:layout_marginStart="16dp"
android:text="1441"
app:layout_constraintBottom_toBottomOf="#+id/imageView2"
app:layout_constraintStart_toEndOf="#+id/imageView2"
app:layout_constraintTop_toTopOf="#+id/imageView2" />
<TextView
android:id="#+id/repo_language_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:layout_marginTop="8dp"
android:text="Ruby"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="#+id/repo_stars_tv"
app:layout_constraintStart_toEndOf="#+id/repo_stars_tv"
app:layout_constraintTop_toTopOf="#+id/repo_stars_tv" />
</LinearLayout>
</LinearLayout>
fragment_github.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".GithubFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/repo_recycler_view"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent" />
</LinearLayout>
You are attaching adapter after getting a response from the API
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
listAdapter = new RecyclerViewRepoAdapter(getContext(), repositories); // List of Github repos to be display
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(listAdapter); // Called from here after response from cloud funtion
Move this code in onCreateView
assert getArguments() != null;
View v = inflater.inflate(R.layout.fragment_github, container, false);
recyclerView = v.findViewById(R.id.repo_recycler_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
listAdapter = new RecyclerViewRepoAdapter(getContext(), repositories); // List of Github repos to be display
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(listAdapter); // Called from here after response from cloud funtion
return v;
And after getting a response from Api in AsyncTask onPostExecute() Method add data into list and notify adapter
ParseResponse parseResponse = new ParseResponse(response);
repositories = parseResponse.getRepositories();
listAdapter.notifyDataSetChanged();

How to use onItemClick in listview that get data from mysql?

I have a custom ListView with a TextView that get data from mysql. What I want to get the content from textview when the item is clicked.
I have tried this,
mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String value = mList.getItemAtPosition(position).toString();
Toast.makeText(getBaseContext(), value, Toast.LENGTH_LONG).show();
}
});
but it returns com.wanto.sispaktriwanto.init.Penyakit#c05cb5c.
Can anyone help me to solve this?
Thanks.
This is model code:
package com.wanto.sispaktriwanto.init;
public class Penyakit {
private String penyakit_nama;
public String getpenyakit_nama() {
return penyakit_nama;
}
public void setpenyakit_nama(String penyakit_nama) {
this.penyakit_nama = penyakit_nama;
}
}
This is code for get data from mysql:
package com.wanto.sispaktriwanto.server;
import com.wanto.sispaktriwanto.init.HasilKonsul;
import com.wanto.sispaktriwanto.init.Penyakit;
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.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
public class GetDetailPenyakit {
public static ArrayList<Penyakit> getDetail(String postvariable) {
String detail = "";
ArrayList<Penyakit> MyArraylist = new ArrayList<>();
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.2.2/android_sispak/getDetailPenyakit.php");
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("detail", postvariable));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
detail = EntityUtils.toString(httpResponse.getEntity());
JSONArray jsonArray = new JSONArray(detail);
for (int i = 0; i < jsonArray.length(); i++) {
Penyakit genres = new Penyakit();
JSONObject MyJsonObject = jsonArray.getJSONObject(i);
genres.setpenyakit_nama(MyJsonObject.getString("nama"));
MyArraylist.add(genres);
}
} catch (Exception e) {
e.printStackTrace();
}
return MyArraylist;
}
}
This is adapter code:
package com.wanto.sispaktriwanto.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import com.wanto.sispaktriwanto.R;
import com.wanto.sispaktriwanto.init.Penyakit;
import java.util.List;
public class PenyakitAdapter extends ArrayAdapter<Penyakit> {
private final List<Penyakit> list;
public PenyakitAdapter(Context context, int resource, List<Penyakit> list) {
super(context, resource, list);
this.list = list;
}
static class ViewHolder {
protected TextView penyakitNama;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
LayoutInflater inflator = LayoutInflater.from(getContext());
convertView = inflator.inflate(R.layout.row_penyakit, null);
viewHolder = new ViewHolder();
viewHolder.penyakitNama = (TextView) convertView.findViewById(R.id.row_namap);
convertView.setTag(viewHolder);
convertView.setTag(R.id.row_namap, viewHolder.penyakitNama);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.penyakitNama.setText(list.get(position).getpenyakit_nama());
return convertView;
}
}
This is activity code:
package com.wanto.sispaktriwanto;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.wanto.sispaktriwanto.adapter.PenyakitAdapter;
import com.wanto.sispaktriwanto.init.Penyakit;
import com.wanto.sispaktriwanto.server.GetDetailPenyakit;
import com.wanto.sispaktriwanto.server.PenyakitJsonParser;
import java.util.ArrayList;
public class DetailPenyakit extends AppCompatActivity {
Context context;
ArrayList<Penyakit> array_list;
GetDetailPenyakit JsonGetDetail;
ListView mList;
String konsultasiS;
static String detailresponse;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_penyakit);
Intent intent = getIntent();
detailresponse = intent.getExtras().getString("detail");
context = this;
new asyncTask_getPenyakit().execute();
}
public class asyncTask_getPenyakit extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog = new ProgressDialog(context);
#Override
protected void onPreExecute() {
dialog.setTitle("Please wait...");
dialog.setMessage("Loading Info Penyakit!");
dialog.show();
array_list = new ArrayList<>();
JsonGetDetail = new GetDetailPenyakit();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
array_list = JsonGetDetail.getDetail(detailresponse);
return null;
}
protected void onPostExecute(Void s) {
mList = (ListView) findViewById(R.id.detail_listView);
final PenyakitAdapter detailAdapter = new PenyakitAdapter(context, R.layout.row_penyakit, array_list);
mList.setAdapter(detailAdapter);
mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String value = mList.getItemAtPosition(position).toString();
Toast.makeText(getBaseContext(), value, Toast.LENGTH_LONG).show();
}
});
super.onPostExecute(s);
dialog.dismiss();
}
}
}
This is activity xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.wanto.sispaktriwanto.DetailPenyakit">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="100">
<ListView
android:id="#+id/detail_listView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:divider="#drawable/divider"
android:dividerHeight="1sp"
android:layout_weight="80"/>
</LinearLayout>
</android.support.constraint.ConstraintLayout>
and row xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:background="#ffffff"
android:orientation="vertical">
<TextView
android:id="#+id/row_namap"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_marginLeft="20dp"
android:maxLines="1"
android:text="sss"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium"/>
</LinearLayout>
By using this code you can get the current value of the textview.
mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String contactId = ((TextView) view.findViewById(R.id.row_namap)).getText().toString();
Toast.makeText(getBaseContext(), value, Toast.LENGTH_LONG).show();
}
});
one mistake is there,
You already have arraylist in your activity so try this,
mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String value = array_list.get(position).getpenyakit_nama();
Toast.makeText(getBaseContext(), value, Toast.LENGTH_LONG).show();
}
});
Do let me know if this works or not
String value = mList.getItemAtPosition(position).toString();
it will be get Penyakit object.
if you want get penyakit_nama value, use below code.
String value = ((Penyakit)mList.getItemAtPosition(position)).getpenyakit_nama();
because generic type of your ArrayAdapter is <Penyakit>, getItemAtPosition() will return Penyakit object

I want to add a "delete button" in custom listview to delete data from firebase and also the image in firebase storage

I am new to android development. Here is a picture of my firebase database.
I am showing the name and an image of the movie in my android application in a custom list view.
Here is my ModelClass
public class ModelClass {
String name,imagelink;
public ModelClass() {
}
public ModelClass(String name, String imagelink) {
this.name = name;
this.imagelink = imagelink;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImagelink() {
return imagelink;
}
public void setImagelink(String imagelink) {
this.imagelink = imagelink;
}
}
Here is my Adapter Class
import android.app.Activity;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.List;
public class MyAdapter extends ArrayAdapter<ModelClass> {
private Activity context;
private int resource;
private List<ModelClass> listImage;
private DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("MovieDetails");
public MyAdapter(#NonNull Activity context, #LayoutRes int resource, #NonNull List<ModelClass> objects) {
super(context, resource, objects);
this.context = context;
this.resource = resource;
listImage = objects;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View v = inflater.inflate(resource, null);
TextView tvName = (TextView) v.findViewById(R.id.movie_name_view);
ImageView img = (ImageView) v.findViewById(R.id.movie_image_view);
tvName.setText(listImage.get(position).getName());
Glide.with(context).load(listImage.get(position).getImagelink()).into(img);
return v;
}
public void addElement(ModelClass element) {
listImage.add(element);
}
}
And This is my Activity
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.TextView;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class CheckMovieInfoActivity extends AppCompatActivity {
private DatabaseReference mDatabaseRef;
private List<ModelClass> imgList;
private ListView lv;
private MyAdapter myAdapter;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_movie_info);
imgList = new ArrayList<>();
lv = (ListView) findViewById(R.id.messagelist);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Please wait loading Images...");
progressDialog.show();
mDatabaseRef = FirebaseDatabase.getInstance().getReference("MovieDetails");
myAdapter = new MyAdapter(CheckMovieInfoActivity.this, R.layout.customlistview, imgList);
lv.setAdapter(myAdapter);
mDatabaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
progressDialog.dismiss();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
ModelClass img = snapshot.getValue(ModelClass.class);
myAdapter.addElement(img);
}
myAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
progressDialog.dismiss();
}
});
}
}
And this is my Custom List View XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="6dp">
<ImageView
android:id="#+id/movie_image_view"
android:layout_width="140dp"
android:layout_height="140dp"
android:src="#drawable/upload_image_small"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/movie_name_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MOVIE NAME"
android:layout_gravity="center"
android:textSize="20dp"/>
</LinearLayout>
</LinearLayout>
<Button
android:layout_marginTop="8dp"
android:id="#+id/btndel"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Delete Movie"
android:background="#drawable/roundedbutton"/>
</LinearLayout>
I want to add a delete button in the custom listview to delete the data and also the image from the database.
I am not getting any errors I just want to add a delete button to delete the data. Thanks in advance.

spinner onitemselected is not working as expected?

I did not add spinner on my layout
I did not use addView function
code
Spinner spinner = new Spinner(MainActivity.this);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, myArray);
spinner.setAdapter(spinnerArrayAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
{
//this place is never called
}
public void onNothingSelected(AdapterView<?> parent)
{
}
});
I called spinner like this:
spinner.performClick();
After this I click one of my item which in my array and then I expect to fire onItemSelected but it never fires.
the problem is
onitemselected is never called.
thanks in advance
Try this,
1.Create a custom adapter.
2.set click Listener to textview in adapter.(so you can get position in adapter)
3.according to positon do whatever u feel like.
CustomModel.
public class CustomModel {
private String id;
private String description;
public char[] name;
public CustomModel() {
}
public CustomModel(String id, String description) {
this.id = id;
this.description = description;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return description;
}
public void setName(String description) {
this.description = description;
}
}
Activity.
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CursorAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import adapter.CustomAdapter;
import models.CustomModel;
import utils.SessionManager;
import static android.R.attr.id;
import static android.R.id.text1;
public class spinner extends AppCompatActivity {
private SessionManager sessionManager;
private List<CustomModel> myArray=new ArrayList<CustomModel>();
CustomModel customModel;
LinearLayout container;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinnre);
container = (LinearLayout) findViewById(R.id.container);
customModel=new CustomModel();
customModel.setName("Select a number");
myArray.add(customModel);
for(int i=0;i<10;i++)
{
customModel=new CustomModel();
customModel.setName(String.valueOf(i));
myArray.add(customModel);
}
LinearLayout.LayoutParams spinnerParamas = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams textParamas = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
spinnerParamas.setMargins(0,50,0,0);
Spinner spinner = new Spinner(spinner.this);
spinner.setLayoutParams(spinnerParamas);
spinner.setId(0);
CustomAdapter customAdapter=new CustomAdapter(spinner.this,myArray,spinner);
spinner.setAdapter(customAdapter);
container.addView(spinner);
}
}
Adapter
import android.app.Activity;
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.Spinner;
import android.widget.TextView;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
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.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.example.ciomp.global.R;
import models.CustomModel;
/**
* Created by ciomp on 11/23/2016.
*/
public class CustomAdapter extends BaseAdapter {
private Context mContext;
private List<CustomModel> mList=new ArrayList<CustomModel>();
private LayoutInflater mLayoutInflater;
private String mType=null;
private Spinner mSpinner;
int one=0;
public CustomAdapter(Context mContext, List<CustomModel> list, Spinner spin) {
this.mContext=mContext;
this.mList=list;
mSpinner=spin;
}
#Override
public int getCount() {
return mList.size();
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
CustomAdapter.ViewHolder holder=null;
LayoutInflater layoutInflater=(LayoutInflater)mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if(convertView==null){
convertView = layoutInflater.inflate(R.layout.customlayout, null);
holder = new CustomAdapter.ViewHolder();
holder.textView2=(TextView)convertView.findViewById(R.id.txt_text1);
convertView.setTag(holder);
}
else {
holder = (CustomAdapter.ViewHolder) convertView.getTag();
}
CustomModel classModel=mList.get(position);
holder.textView2.setText(classModel.getName());
holder.textView2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(one==0)
{
mSpinner.performClick();
one=1;
}
else if(one==1)
{
Toast.makeText(mContext, mList.get(position).getName(), Toast.LENGTH_SHORT).show();
try {
Method method = Spinner.class.getDeclaredMethod("onDetachedFromWindow");
method.setAccessible(true);
method.invoke(mSpinner);
} catch (Exception e) {
e.printStackTrace();
}
one=0;
}
}
});
return convertView;
}
static class ViewHolder{
TextView textView2;
}
}
spinnre.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_marginRight="5dp"
android:layout_marginBottom="10dp"
android:layout_marginLeft="5dp"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
</LinearLayout>
customlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/txt_text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="14sp"
android:layout_marginBottom="13dp"
android:gravity="center"
android:layout_marginTop="13dp"
android:layout_marginLeft="5dp"
android:paddingLeft="5dp"
android:textColor="#000"
/>
/>
</LinearLayout>
hope it may help you.
In order to programatically select item from spinner. you need to call
spinner.setSelection(1);
Whereas 1 in the index, you want to select

Custom ListView not showing any items

I am trying to display a custom listview but nothing appears.
My activity:
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import com.example.elnoorgeh.ServerAPI;
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class BlogFragment extends Fragment {
JSONArray jArray;
TextView title;
RelativeLayout layout;
int previousID = 0;
int currentID = 0;
ArrayList<String> titles;
ArrayList<String> contents;
ListView list;
public BlogFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_blog, container,
false);
new AsyncFetch().execute();
return rootView;
}
private class AsyncFetch extends AsyncTask<Object, Object, Object> {
#Override
protected Object doInBackground(Object... params) {
// TODO Auto-generated method stub
jArray = new JSONArray();
jArray = ServerAPI.getData();
titles = new ArrayList<String>();
contents = new ArrayList<String>();
for (int i = 0; i < jArray.length(); i++) {
String blogTitle = null;
String content = null;
try {
blogTitle = jArray.getJSONObject(i).getString("title");
content = jArray.getJSONObject(i).getString("content");
titles.add(blogTitle);
contents.add(content);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println(blogTitle);
System.out.println(content);
}
// display(titles, contents);
return null;
}
protected void onPostExecute(Object result) {
layout = (RelativeLayout) getView().findViewById(R.id.blogPage);
layout.removeAllViews();
CustomList adapter = new CustomList(getActivity(), titles);
list = new ListView(getActivity());
System.out.println("list done");
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getActivity(),
"You Clicked at " + titles.get(position),
Toast.LENGTH_SHORT).show();
}
});
}
}
public void display(ArrayList<String> t, ArrayList<String> c) {
}
}
Custom ListView class:
import java.util.ArrayList;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomList extends ArrayAdapter<String> {
private final Activity context;
private final ArrayList<String> web;
// private final Integer[] imageId;
public CustomList(Activity context, ArrayList<String>web) {
super(context, R.layout.fragment_listview);
this.context = context;
this.web = web;
// this.imageId = imageId;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.fragment_listview, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
txtTitle.setText((CharSequence) web.get(position));
// imageView.setImageResource(imageId[position]);
return rowView;
}
}
fragment_blog:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/blogPage"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
<TextView
android:id="#+id/txtLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:maxLines="20"
android:singleLine="false"
android:textSize="16dp" />
</RelativeLayout>
fragment_listview:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TableRow>
<ImageView
android:id="#+id/img"
android:layout_width="50dp"
android:layout_height="50dp" />
<TextView
android:id="#+id/txt"
android:layout_width="wrap_content"
android:layout_height="50dp" />
</TableRow>
</TableLayout>
I can't find any errors or notice something irregular, so why is that happening?
you should extend BaseAdapter and implement abstract methods
#Override
public int getCount() {
return web.size();
}
#Override
public Object getItem(int position) {
return web.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
also you might change
txtTitle.setText((CharSequence) web.get(position));
to
txtTitle.setText((CharSequence) getItem(position));
now your adapter don't know size of web array
edit:
you can get one inflater in constructor and keep in class, no need to getting inflater each time (little bit better for perfomance)
LayoutInflater inflater = context.getLayoutInflater();
edit 2:
localhost put proper comment - you are removing all Views from RelativeLayout, also ListView, and creating new ListView without adding to Relative. keeping reference will not auto-add View
protected void onPostExecute(Object result) {
layout = (RelativeLayout) getView().findViewById(R.id.blogPage);
layout.removeView(getView().findViewById(R.id.txtLabel);
//assuming you need to remove only txtLabel
CustomList adapter = new CustomList(getActivity(), titles);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getActivity(),
"You Clicked at " + titles.get(position),
Toast.LENGTH_SHORT).show();
}
});
}

Categories

Resources