How to change ListView to RecyclerView in Android Studio? - android

I don't know how to use RecyclerView to replace ListView. Anyone can help me? Thank you. I find out so many resources in the different online platform but I don't know how to change my code. When I trying to alter my code, it doesn't work.
Code is in the following:
MainActivity.java
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = "https://api.androidhive.info/contacts/";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("contacts");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String email = c.getString("email");
String address = c.getString("address");
String gender = c.getString("gender");
// Phone node is JSON Object
JSONObject phone = c.getJSONObject("phone");
String mobile = phone.getString("mobile");
String home = phone.getString("home");
String office = phone.getString("office");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("id", id);
contact.put("name", name);
contact.put("email", email);
contact.put("mobile", mobile);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[]{"name", "email",
"mobile"}, new int[]{R.id.name,
R.id.email, R.id.mobile});
lv.setAdapter(adapter);
}
}
}
HttpHandler.java
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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="hk.edu.ouhk.android.jsonparsing.MainActivity">
<ListView
android:id="#+id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dip">
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:paddingTop="6dip"
android:textColor="#color/colorPrimaryDark"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="#+id/email"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="#5d5d5d" />
<TextView
android:id="#+id/mobile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#686868"
android:textStyle="bold" />
</LinearLayout>

as you seems to have no problem getting data from url and you successfully have made an Arraylist from the data
steps to follow now
1. add recyclerview to xml of your activity
2. make a layout how you want to display data in recyclerview items
3. then you need to make an adapter that takes data you provide and binds it to
recycler view
4. then add adapter to your recycler view
I am attaching simple recycler view which I made a while ago for me. It is simple and self explanatory. Otherwise you can comment I will explain it more
Main Activity
public class MainActivity extends AppCompatActivity {
ArrayList<String> moviesList;
RecyclerView recyclerView;
RecyclerAdapter recyclerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
moviesList=new ArrayList<>();
recyclerView=findViewById(R.id.recyclerView);
recyclerAdapter=new RecyclerAdapter(moviesList);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(recyclerAdapter);
moviesList.add("Kapil");
moviesList.add("Kapil");
moviesList.add("Kapil");
moviesList.add("Kapil");
moviesList.add("Kapil");
moviesList.add("Kapil");
moviesList.add("Kapil"); }
}
RecyclerAdapter in this we are creating custom viewholder for us
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder>
{
public RecyclerAdapter(ArrayList<String> moviesList) {
this.moviesList = moviesList;
}
ArrayList<String> moviesList;
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater=LayoutInflater.from(parent.getContext());
View view=layoutInflater.inflate(R.layout.row_layout,parent,false);
ViewHolder viewHolder= new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.rowTextView.setText(String.valueOf(position));
holder.textView.setText(moviesList.get(position));
}
#Override
public int getItemCount() {
return moviesList.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
TextView textView,rowTextView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView=itemView.findViewById(R.id.imageView);
textView=itemView.findViewById(R.id.textView);
rowTextView=itemView.findViewById(R.id.rowTextView);
}
}
}
This is layout for the item which I want to show in recycler view
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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="wrap_content">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="22dp"
android:layout_marginTop="16dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_launcher_background" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginTop="22dp"
android:text="TextView"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
app:layout_constraintStart_toEndOf="#+id/imageView"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/rowTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="33dp"
android:layout_marginTop="16dp"
android:text="TextView"
app:layout_constraintStart_toEndOf="#+id/imageView"
app:layout_constraintTop_toBottomOf="#+id/textView" />
</androidx.constraintlayout.widget.ConstraintLayout>
Just pass your array list to it. Like i did

Basically you need to create RecyclerViewAdapter with ViewHolder pattern, and just simply replace ListView to RecyclerView

Related

how to use floating search view with a list view loaded by json?

I load a list view using json ,this is work fine.Now i want to add a floating search view to this list .I dont know how use it correcte and how to implement my own searchable function.can you some one help me.
this is my code in main activity :
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
EditText textView;
Spinner s;
// Search EditText
EditText inputSearch;
FloatingSearchView mSearchView;
// URL to get contacts JSON
// private static String url ="http://10.3.216.241/WorkServIndus.nsf/ListeClient.xsp/ListeClient";
private static String url ="http://myadress/WorkServIndus.nsf/ListeClient.xsp/ListeClient";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
// s=(Spinner)findViewById(R.id.spinner);
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
//JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = new JSONArray(jsonStr);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
// return new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
String test=c.getString("ServiFournisseur");
String name = c.getString("universalID");
final String localite=c.getString("Localite");
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("universalID", name);
contact.put("ServiFournisseur", test);
// contact.put("Localite", localite);
// contact.put("ServiFournisseur", lt_name);
// contact.put("location", location);
// adding contact to contact list
contactList.add(contact);
// String lt_name = c.getString("ServiFournisseur");
// String location = c.getString("location");
// return new JSONObject(jsonStr.substring(jsonStr.indexOf("{"), jsonObj.lastIndexOf("}") + 1));
// tmp hash map for single contact
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[]{"universalID","ServiFournisseur"
}, new int[]{R.id.name,R.id.email
});
lv.setAdapter(adapter);
}
}
this is my class for connection :
public class HttpHandler
{
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
this is the main layout :
<?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="tn.servi.mytest.MainActivity">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<com.arlib.floatingsearchview.FloatingSearchView
android:id="#+id/floating_search_view"
android:layout_width="wrap_content"
android:layout_height="66dp"
app:floatingSearch_close_search_on_keyboard_dismiss="true"
app:floatingSearch_leftActionMode="showHamburger"
app:floatingSearch_searchBarMarginLeft="#dimen/search_view_inset"
app:floatingSearch_searchBarMarginRight="#dimen/search_view_inset"
app:floatingSearch_searchBarMarginTop="#dimen/search_view_inset"
app:floatingSearch_searchHint="Search..."
app:floatingSearch_showSearchKey="false"
app:floatingSearch_suggestionsListAnimDuration="250" />
<!-- List View -->
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</android.support.constraint.ConstraintLayout>
list_item.xml :
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="213dp"
android:orientation="vertical"
android:paddingLeft="24dp"
android:paddingRight="24dp"
android:paddingTop="56dp"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="16dp"
tools:ignore="MissingConstraints">
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:textColor="#color/colorPrimaryDark"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp" />
<TextView
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="#color/colorAccent" />
</LinearLayout>
</android.support.constraint.ConstraintLayout>
mSearchView.setOnQueryChangeListener(new FloatingSearchView.OnQueryChangeListener() {
#Override
public void onSearchTextChanged(String oldQuery, final String newQuery) {
//get suggestions based on newQuery
//pass them on to the search view
mSearchView.swapSuggestions(newSuggestions);
}
});

Android: add different links in button:onclick for each button in listview

I'm getting json of news articles from a website and displaying the article titles + summaries in a listview. Below each summary, I would like to add a 'read more' button which will open the browser and visit that specific article on the website.
However, how do I manage to make each 'read more' button link to the specific news article instead of every button to the same general website? Code below:
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get articles JSON
private static String url = "http://www.sample.com/json";
ArrayList<HashMap<String, String>> newsList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
newsList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetArticles().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetArticles extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray articles = jsonObj.getJSONArray("articles");
// looping through All Contacts
for (int i = 0; i < articles.length(); i++) {
JSONObject c = articles.getJSONObject(i);
String title = c.getString("title");
String description = c.getString("description");
String weblink = c.getString("weblink");
// tmp hash map for single contact
HashMap<String, String> article = new HashMap<>();
// adding each child node to HashMap key => value
article.put("title", weblink);
article.put("description", weblink);
article.put("weblink", weblink);
// adding contact to contact list
newsList.add(article);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, newsList,
R.layout.list_item, new String[]{"title",
"description"}, new int[]{R.id.title,
R.id.description});
lv.setAdapter(adapter);
}
}
/** Called when the user clicks the read more button */
public void visitWebsite(View view) {
Uri uri = Uri.parse("http://www.sample.com");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
}
And list_item.xml below:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="#dimen/activity_horizontal_margin">
<TextView
android:id="#+id/title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:paddingTop="6dip"
android:textColor="#color/colorPrimaryDark"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="#+id/description"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="#color/colorAccent" />
<Button
android:id="#+id/weblink"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="read more"
android:onClick="visitWebsite" />
</LinearLayout>
And activity_main.xml below
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="nl.ttvavanti.avanti.MainActivity">
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
You can put/get different URLs as TAG by .setTag() and getTag() methods like in this answer.
public void visitWebsite(View view) {
Uri uri = Uri.parse(view.getTag().toString);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
I suggest to try using an ArrayAdapter instead of a SimpleAdapter and in the array adapter use an OnclickListener over the Button
Like in this example https://www.sitepoint.com/custom-data-layouts-with-your-own-android-arrayadapter/

ListView Not Working On Real Device

I have a problem with my listview, it works on emulator but not on real device. I tested with 2 real devices and it does not populate. I get listview data from database using json. Json result is ok as it prints to logcat and populates listview on emulator.
ListView Java:
public class ActivityRequestsFrom extends MainActivity implements AdapterView.OnItemClickListener {
______________________________________________________________________________
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_requests_from);
lv = (ListView) findViewById(R.id.listRequests);
RequestsAdapter adapter = new RequestsAdapter(this, arrRequest_Name, arrRequest_Number,
arrRequest_Username, arrRequest_Result, imageId);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);
}
______________________________________________________________________________
class RequestsAdapter extends ArrayAdapter<String>
{
Context context;
List<String> Request_Name;
List<String> Request_Number;
List<String> Request_Username;
List<String> Request_Result;
Integer[] imgid;
RequestsAdapter(Context c, List<String> Request_Name,
List<String> Request_Number, List<String> Request_Username,
List<String> Request_Result, Integer[] imgid)
{
super(c, R.layout.activity_requests_single, R.id.textName, Request_Name);
this.context=c;
this.Request_Name=Request_Name;
this.Request_Number=Request_Number;
this.Request_Username=Request_Username;
this.Request_Result=Request_Result;
this.imgid=imgid;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row=convertView;
if(row==null)
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.activity_requests_single, parent, false); }
TextView txtName = (TextView) row.findViewById(R.id.textName);
TextView txtNumber = (TextView) row.findViewById(R.id.textNumber);
TextView txtUsername = (TextView) row.findViewById(R.id.textUsername);
TextView txtResult = (TextView) row.findViewById(R.id.textResult);
ImageView imageView = (ImageView) row.findViewById(R.id.imageView);
Map<String, Integer> drawableMap = new HashMap<String, Integer>();
drawableMap.put("ok",R.drawable.request_pending_from);
drawableMap.put("pending",R.drawable.request_pending_from);
drawableMap.put("rejected",R.drawable.request_rejected_from);
drawableMap.put("blocked",R.drawable.request_blocked_from);
txtName.setText(Request_Name.get(position));
txtNumber.setText(Request_Number.get(position));
txtUsername.setText(Request_Username.get(position));
txtResult.setText(Request_Result.get(position));
//imageView.setImageResource(imgid[position]);
imageView.setImageResource(drawableMap.get(Request_Result.get(position).toLowerCase()));
return row;
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
TextView tvUsername = (TextView) view.findViewById(R.id.textUsername);
usernameSelected = tvUsername.getText().toString();
TextView tvResult = (TextView) view.findViewById(R.id.textResult);
resultSelected = tvResult.getText().toString();
if (resultSelected.equals("Pending"))
{
pendingOptions();
}
else if (resultSelected.equals("Rejected"))
{
rejectedOptions();
}
else if (resultSelected.equals("Blocked"))
{
blockedOptions();
}
else
{
}
}
ListView Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/listRequest"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
</ListView>
ListView Single Layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/LLdummy"
android:text="Name"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textStyle="italic"
android:layout_marginLeft="10dp"
/>
<TextView
android:id="#+id/textUsername"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textNumber"
android:layout_alignParentRight="true"
android:layout_below="#+id/textNumber"
android:text="Username"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/textNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textName"
android:layout_below="#+id/textName"
android:text="Number"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textStyle="bold" />
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/LLdummy"
android:layout_centerVertical="true"
android:src="#drawable/request_pending_to" />
Json
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) {
try{
ListDrwaer(); //has ConnectionException (when it cannot reach server)
}catch (Exception e){
Toast.makeText(getApplicationContext(), "Please check your connection..", Toast.LENGTH_LONG).show();
}
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { "http://server/file.php?pIMEI="+IMEI });
}
// build hash set for list view
public void ListDrwaer() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("request_info");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String request_name = jsonChildNode.optString("Request_Name");
String request_number = jsonChildNode.optString("Request_Number");
String request_username = jsonChildNode.optString("Request_Username");
String request_result = jsonChildNode.optString("Request_Result");
arrRequest_Name.add(request_name);
arrRequest_Number.add(request_number);
arrRequest_Username.add(request_username);
arrRequest_Result.add(request_result);
System.out.println("Request_Name: "+request_name);
System.out.println("Request_Number: "+request_number);
System.out.println("Request_Username: "+request_username);
System.out.println("Request_Result: "+request_result);
}
} catch (JSONException e) {
System.out.println("Json Error Requests" +e.toString());
Toast.makeText(getApplicationContext(), "No Requests Pending", Toast.LENGTH_SHORT).show();
}
}
Call Async
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_requests_from);
...
accessWebService();
//ListView
lv = (ListView) findViewById(R.id.listRequests);
RequestsAdapter adapter = new RequestsAdapter(this, arrRequest_Name, arrRequest_Number, arrRequest_Username, arrRequest_Result, imageId);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);
The problem here is that the data isn't received when the Adapter is set on the ListView. This is because the data is populated in an AysncTask which is async hronous by nature. This means that it will run in the background while the other code runs (i.e. the ListView populating.
So, in onPostExecute() you need to use notifyDataSetChanged() to let the ListView know that there is new items to populate.
#Override
protected void onPostExecute(String result) {
// your code
adapter.notifyDataSetChanged(); // this line here
}// end async task
In your example, this will obviously require you making the Adapter a member variable or passing it to your AsyncTask.

JSONArray to ListView - AsyncTask

I am currently using an activity with two buttons and a textview. In the textview i put an id of what orders i want to get from the database through php. Then i use the getJSON button which gets the data and afterwards i currently need tu press parseJSON which opens the list. I would like it to be enough pressing one of the buttons, and while fetching the data showing an dialog saying loading.
I am currently using the code below
FetchOrderList.java
public class FetchOrderList extends AppCompatActivity {
String json_string;
SQL akep = new SQL();
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
}
//Called when pressing getJSON (The first button)
public void getJSON(View view) {
TextView txt = (TextView) findViewById(R.id.editText);
new BackgroundTask(txt.getText().toString()).execute();
}
class BackgroundTask extends AsyncTask<Void, Void, String>
{
String json_url = "MYURL";
String JSON_STRING;
String sendID;
protected BackgroundTask(String id){
sendID = id;
}
#Override
protected String doInBackground(Void... params) {
String data;
try {
data = URLEncoder.encode("id", "UTF-8") + "=" + URLEncoder.encode(sendID, "UTF-8");
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(httpURLConnection.getOutputStream());
wr.write(data);
wr.flush();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((JSON_STRING = bufferedReader.readLine())!=null)
{
stringBuilder.append(JSON_STRING+"\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(result);
json_string = result;
}
}
//Called when pressing the parseJSON button (The second button)
public void parseJSON(View view)
{
if(json_string==null)
{
Toast.makeText(getApplicationContext(), "First Get JSON", Toast.LENGTH_LONG).show();
}
else
{
Intent intent = new Intent(this, DisplayListView.class);
intent.putExtra("json_data", json_string);
startActivity(intent);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GET JSON"
android:id="#+id/b1"
android:background="#989898"
android:onClick="getJSON"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="PARSE JSON"
android:id="#+id/b2"
android:background="#989898"
android:onClick="parseJSON"
android:layout_marginTop="46dp"
android:layout_below="#+id/editText"
android:layout_alignParentEnd="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="100dp"
android:layout_height="30dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/textView"
android:layout_below="#+id/b2"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="20dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/editText"
android:hint="Tur id"
android:gravity="center"
android:onClick="getJSON"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
DisplayListView.java
public class DisplayListView extends AppCompatActivity {
String json_string;
JSONObject jsonObject;
JSONArray jsonArray;
ContactAdapter contactAdapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_list_view);
getSupportActionBar().hide();
listView = (ListView)findViewById(R.id.listview);
contactAdapter = new ContactAdapter(this, R.layout.row_layout);
listView.setAdapter(contactAdapter);
json_string = getIntent().getExtras().getString("json_data");
try {
jsonObject = new JSONObject(json_string);
jsonArray = jsonObject.getJSONArray("akep_orders");
int count = 0;
String id, customer_id, customer_name;
while(count<jsonArray.length()) {
JSONObject JO = jsonArray.getJSONObject(count);
id = JO.getString("id");
customer_id = JO.getString("customer_id");
customer_name = JO.getString("customer_name");
Contacts contacts = new Contacts(id, customer_id, customer_name);
contactAdapter.add(contacts);
count++;
}
} catch (JSONException e) {
e.printStackTrace();
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView theid = (TextView)view.findViewById(R.id.tx_id);
TextView thecustomerid = (TextView)view.findViewById(R.id.tx_customerid);
TextView thecustomername = (TextView)view.findViewById(R.id.tx_customername);
String itemId = theid.getText().toString();
String itemCustomerid = thecustomerid.getText().toString();
String itemCustomername = thecustomername.getText().toString();
Intent intent = new Intent(DisplayListView.this, OrderView.class);
intent.putExtra("id", itemId);
intent.putExtra("cid", itemCustomerid);
intent.putExtra("cname", itemCustomername);
startActivity(intent);
}
});
}
Use setOnLongPressClickListner method for long button press.

Populating a list using android listview

I am trying to populate the result onto a listview once I press the search button. But, when i try to do it, nothing is displayed on the listview.
I am using asynctask to get the data from database and pass it into the listview as a array.
Thanks for the help in advance!
Below are the code:
public class FindFriends extends Activity implements View.OnClickListener {
EditText handphone;
Button searchbtn;
String name,hp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.findfriends);
handphone = (EditText) findViewById(R.id.enterfn);
searchbtn = (Button) findViewById(R.id.searchfor);
searchbtn.setOnClickListener(this);
ListView listview = (ListView) findViewById(R.id.listView);
String[] values = new String[]{name};
ArrayAdapter<String> codeLearnArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values);
listview.setAdapter(codeLearnArrayAdapter);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.searchfor:
hp = handphone.getText().toString();
new AttemptLogin().execute(hp);
break;
}
}
class AttemptLogin extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "address_url";
#Override
protected JSONObject doInBackground(String... args) {
// TODO Auto-generated method stub
// here Check for success tag
try {
HashMap<String, String> params = new HashMap<>();
params.put("hp", args[0]);
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(JSONObject json) {
if (json != null) {
Toast.makeText(FindFriends.this, json.toString(),
Toast.LENGTH_LONG).show();
try {
name = json.getString("name");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
findfriends.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:background="#drawable/findfriends"
android:layout_height="match_parent">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/enterfn"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter handphone number/username to start searching"
android:id="#+id/textView9"
android:textSize="20dp"
android:layout_above="#+id/enterfn"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search"
android:id="#+id/searchfor"
android:layout_below="#+id/enterfn"
android:layout_centerHorizontal="true" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_below="#+id/searchfor"
android:layout_centerHorizontal="true" />
</RelativeLayout>
I'm new in Android.
Anyway I can't see where you update your array, in the AsyncTask you download the data but you don't update values. So you shuld update the array passed to the adapter and then call the it's method notifyDataSetChanged()
Just go through the below code and replcae it with your,
public class FindFriends extends Activity implements View.OnClickListener {
EditText handphone;
Button searchbtn;
String name = "name", hp = "hp";
ListView listview;
ArrayAdapter<String> codeLearnArrayAdapter;
ArrayList<String> values;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.findfriends);
handphone = (EditText) findViewById(R.id.enterfn);
searchbtn = (Button) findViewById(R.id.searchfor);
searchbtn.setOnClickListener(this);
listview = (ListView) findViewById(R.id.listView);
// adding value to arrayList
values.add(name);
codeLearnArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values);
listview.setAdapter(codeLearnArrayAdapter);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.searchfor:
hp = handphone.getText().toString();
new AttemptLogin(new MyHandler()).execute(hp);
break;
}
}
class AttemptLogin extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "address_url";
MyHandler myHandler;
public AttemptLogin(MyHandler myHandler) {
this.myHandler = myHandler;
}
#Override
protected JSONObject doInBackground(String... args) {
// TODO Auto-generated method stub
// here Check for success tag
try {
HashMap<String, String> params = new HashMap<>();
params.put("hp", args[0]);
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(JSONObject json) {
if (json != null) {
Toast.makeText(FindFriends.this, json.toString(),
Toast.LENGTH_LONG).show();
try {
name = json.getString("name");
Message message = new Message();
message.obj = name;
myHandler.sendMessage(message);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
private class MyHandler extends Handler {
#Override
public void handleMessage(Message msg) {
String response = String.valueOf(msg);
values.add(response);
codeLearnArrayAdapter.notifyDataSetChanged();
}
}
}
And let me know if it works...
you missed adapter.notifyDataSetChanged();
Use this method after data changing
UPD
try this code:
protected void onPostExecute(JSONObject json) {
if (json != null) {
Toast.makeText(FindFriends.this, json.toString(),
Toast.LENGTH_LONG).show();
try {
name = json.getString("name");
values[0]=name;
codeLearnArrayAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Hope it works. Otherwise let me know about it.
P.S. You should also use List instead of array.

Categories

Resources