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.
Related
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
I have a class which extends listactivity. I am parsing data from a json file and putting data in list. i have also created a checkbox to check student is present if it checked. For that i have created an array to get the position from list. I am getting the student names but checkbox is giving me null values. Please Help!!! Here is my code,
public class Student_data extends ListActivity {
private ProgressDialog pDialog;
private Button button;
ListView lv;
// URL to get contacts JSON
private static String url = "http://10.0.2.2/studentdata.json";
private static int[] present, absent;
private static int i = 0, j = 0, x;
// JSON Node names
private static final String TAG_DEP_ID = "dep_id";
private static final String TAG_HEAD = "stdata";
private static final String TAG_NAME = "name";
private static final String TAG_ENROLL = "enrollment";
// contacts JSONArray
JSONArray data = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> studentList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.student_list);
studentList = new ArrayList<HashMap<String, String>>();
button = (Button) findViewById(R.id.saveData);
button.setOnClickListener(new ButtonClick());
lv = getListView();
new GetContacts().execute();
lv.setOnItemClickListener(new CheckBoxClick());
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(Student_data.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
data = jsonObj.getJSONArray(TAG_HEAD);
// looping through All Contacts
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
String id = c.getString(TAG_DEP_ID);
String name = c.getString(TAG_NAME);
String enrll = c.getString(TAG_ENROLL);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_DEP_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_ENROLL, enrll);
// adding contact to contact list
studentList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
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(Student_data.this, studentList, R.layout.data_item,
new String[] { TAG_NAME }, new int[] { R.id.name });
setListAdapter(adapter);
}
}
public class CheckBoxClick implements OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
CheckBox chkbox = (CheckBox) arg1;
if (chkbox.isChecked()) {
present[i] = arg2;
i++;
}
if (chkbox.isChecked()) {
absent[j] = arg2;
j++;
}
}
}
public class ButtonClick implements OnClickListener {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
}
}
data_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="horizontal"
android:padding="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:weightSum="2" >
<!-- Name Label -->
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:paddingBottom="2dip"
android:paddingTop="6dip"
android:textColor="#000"
android:textSize="16sp"
android:textStyle="bold" />
<CheckBox
android:id="#+id/chkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
Try this
if (((CheckBox) arg1).isChecked()) {
//your code
}
I get throuble for view my Spinner Data in XML.
The Toast can show data in selected item, but in spinner view can't show all item.
My code Java
public class LoadCategoryTask extends AsyncTask<Void, Void, Boolean> {
LoadCategoryTask() {
}
#Override
protected Boolean doInBackground(Void... params) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
return false;
}
List<NameValuePair> data = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url_get_category, "GET", data);
Log.d("All Category: ", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
category = json.getJSONArray(TAG_CATEGORY);
for (int i = 0; i < category.length(); i++) {
JSONObject c = category.getJSONObject(i);
String id = c.getString(TAG_ID_CATEGORY);
String category = c.getString(TAG_CATEGORY);
HashMap<String, String> map = new HashMap<String, String>();
System.out.println(id + ", " + category);
map.put(TAG_ID_CATEGORY, id);
map.put(TAG_CATEGORY, category);
category_arraylist.add(map);
}
} else {
System.out.println("Category not found");
}
} catch (JSONException e) {
e.printStackTrace();
}
return true;
}
#Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
simpleAdapter = new SimpleAdapter(PlacesActivity.this, category_arraylist, R.layout.adapter_spinner_category,
new String[] { "category" },new int[]{R.id.lbl_category});
simpleAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
SimpleAdapter.ViewBinder viewBinder = new SimpleAdapter.ViewBinder() {
public boolean setViewValue(View view, Object data,String textRepresentation) {
TextView textView = (TextView) view;
textView.setTextColor(Color.BLACK);
textView.setText(textRepresentation);
return true;
}
};
simpleAdapter.setViewBinder(viewBinder);
sp_category.setAdapter(simpleAdapter);
sp_category.requestFocus();
}
}
#Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
And this XML Code the Activity, activity_places.xml
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/sp_categoriy"
android:theme="#style/Base.Widget.AppCompat.Spinner.Underlined" />
This XML Code for Adapter Spinner, adapter_spinner_category.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">
<TextView
android:id="#+id/lbl_category"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/navigationBarColor"/>
</LinearLayout>
Thanks.
Try This:
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(Contex, R.layout.spinner_textview, ArrayOfElements);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerArrayAdapter);
simple_spinner_dropdown_item layout doesn't have 'lbl_category' id inside.
Make your custom DropDownView layout (just copy simple_spinner_dropdown_item) and set id 'lbl_category' to its CheckedTextView.
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.
I done a populating spinner with JSON.But I got a Error in ArrayList: WorldPopulation cannot be resolved.
public class MainActivity extends Activity {
JSONObject jsonobject;
JSONArray jsonarray;
ProgressDialog mProgressDialog;
ArrayList<String> worldlist;
ArrayList<WorldPopulation> world;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new DownloadJSON().execute();
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
world = new ArrayList<WorldPopulation>();
worldlist = new ArrayList<String>();
jsonobject = JSONfunctions
.getJSONfromURL("http://www.androidbegin.com/tutorial/jsonparsetutorial.txt"); //JSON Functions cannot be resolved Error occured
try {
jsonarray = jsonobject.getJSONArray("worldpopulation");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
WorldPopulation worldpop = new WorldPopulation();
worldpop.setRank(jsonobject.optString("rank"));
worldpop.setCountry(jsonobject.optString("country"));
worldpop.setPopulation(jsonobject.optString("population"));
worldpop.setFlag(jsonobject.optString("flag"));
world.add(worldpop);
worldlist.add(jsonobject.optString("country"));
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
Spinner mySpinner = (Spinner) findViewById(R.id.my_spinner);
mySpinner
.setAdapter(new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_dropdown_item,
worldlist));
mySpinner
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
TextView txtrank = (TextView) findViewById(R.id.rank);
TextView txtcountry = (TextView) findViewById(R.id.country);
TextView txtpopulation = (TextView) findViewById(R.id.population);
txtrank.setText("Rank : "
+ world.get(position).getRank());
txtcountry.setText("Country : "
+ world.get(position).getCountry());
txtpopulation.setText("Population : "
+ world.get(position).getPopulation());
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
}
That Same kind of ArrayList error occured many lines in a code.In xml Coding Everything was fine.Anybody tell me how to solve it.
From the link posted it looks like a incomplete tutorial.
//JSON Functions cannot be resolved Error occured
So the tutorial is missing JSONFunctions class and WorldPopulation class.
Have the below and keep the rest of the code the same.
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
{
#Override
protected Void doInBackground(Void... params) {
world = new ArrayList<WorldPopulation>();
worldlist = new ArrayList<String>();
try
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet("http://www.androidbegin.com/tutorial/jsonparsetutorial.txt");
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
String _response=EntityUtils.toString(resEntity);
Log.i("Response is......................",""+_response);
jsonobject = new JSONObject(_response);
jsonarray = jsonobject.getJSONArray("worldpopulation");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
WorldPopulation worldpop = new WorldPopulation();
worldpop.setRank(jsonobject.optString("rank"));
worldpop.setCountry(jsonobject.optString("country"));
worldpop.setPopulation(jsonobject.optString("population"));
worldpop.setFlag(jsonobject.optString("flag"));
world.add(worldpop);
worldlist.add(jsonobject.optString("country"));
}catch(Exception e)
{
}
return null;
}
Edit:
public class MainActivity extends Activity {
JSONObject jsonobject;
JSONArray jsonarray;
ProgressDialog mProgressDialog;
ArrayList<String> worldlist;
ArrayList<WorldPopulation> world;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new DownloadJSON().execute();
}
private class DownloadJSON extends AsyncTask<Void, Void, Void>
{
#Override
protected Void doInBackground(Void... params) {
world = new ArrayList<WorldPopulation>();
worldlist = new ArrayList<String>();
try
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet("http://www.androidbegin.com/tutorial/jsonparsetutorial.txt");
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
String _response=EntityUtils.toString(resEntity);
Log.i("Response is......................",""+_response);
jsonobject = new JSONObject(_response);
jsonarray = jsonobject.getJSONArray("worldpopulation");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
WorldPopulation worldpop = new WorldPopulation();
worldpop.setRank(jsonobject.optString("rank"));
worldpop.setCountry(jsonobject.optString("country"));
worldpop.setPopulation(jsonobject.optString("population"));
worldpop.setFlag(jsonobject.optString("flag"));
world.add(worldpop);
worldlist.add(jsonobject.optString("country"));
}
}catch(Exception e)
{
}
return null;
}
protected void onPostExecute(Void args) {
// Locate the spinner in activity_main.xml
Spinner mySpinner = (Spinner) findViewById(R.id.my_spinner);
// Spinner adapter
mySpinner
.setAdapter(new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_dropdown_item,
worldlist));
// Spinner on item click listener
mySpinner
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
// TODO Auto-generated method stub
// Locate the textviews in activity_main.xml
TextView txtrank = (TextView) findViewById(R.id.rank);
TextView txtcountry = (TextView) findViewById(R.id.country);
TextView txtpopulation = (TextView) findViewById(R.id.population);
// Set the text followed by the position
txtrank.setText("Rank : "
+ world.get(position).getRank());
txtcountry.setText("Country : "
+ world.get(position).getCountry());
txtpopulation.setText("Population : "
+ world.get(position).getPopulation());
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
}
WorldPopulation.java
public class WorldPopulation {
String rank,country,population,flag;
public String getRank() {
return rank;
}
public void setRank(String rank) {
this.rank = rank;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getPopulation() {
return population;
}
public void setPopulation(String population) {
this.population = population;
}
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
}
activity_main.cml
<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" >
<Spinner
android:id="#+id/my_spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/rank"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/my_spinner" />
<TextView
android:id="#+id/country"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/rank" />
<TextView
android:id="#+id/population"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/country" />
</RelativeLayout>
Snap
Not sure if there is no problem with your WorldPopulation class and its object. I just saw the link again, its not mentioned anywhere what WorldPopulation is,i think it should be a java class- WorldPopulation.java. If you add that, your code should run properly.
It should be like:
public class WorldPopulation {
String rank;
String country;
String population;
String flag;
// getter setters here
//toString if you want
}
i would suggest use Gson instead of a Json Parser. You already have the model class of WorldPopulation, now.. (this will go for all json responses)
Gson gson = new Gson();
ModelClass modelClass= new ModelClass();
modelClass= gson.fromJson(responseContent,ModelClass.class);
https://code.google.com/p/google-gson/
For Naming discrepancies(according to the variables in webservice), can use annotations like #SerializedName. (So no need to use Serializable)
In your case responseContent string can just be jObject.get("worldpopulation"), can also make a class containing ArrayList object which will act as a container for the actual response..no need of extracting jobject then