JSONArray to ListView - AsyncTask - android

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.

Related

How to change ListView to RecyclerView in Android Studio?

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

How to display a listview and a webview in one Activity?

So I'm trying to implement two API in one Activity, and display both the listview and a webview for my second API in the same Activity. I managed to get the listview down. This is part of the MainActivity where I'm trying to call both run both API's through the onClick method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.twit_list);
activity = this;
Key = getStringFromManifest("CONSUMER_KEY");
Secret = getStringFromManifest("CONSUMER_SECRET");
txtSearch = (EditText) findViewById(R.id.txtSearch);
searchbtn = (Button) findViewById(R.id.searchbtn);
save = (Button) findViewById(R.id.save);
savedSearches = (Button)findViewById(R.id.savedSearches);
searchbtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
downloadSearches();
new GoogleSearch();
}
});
save.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
saveSearch();
}
});
savedSearches.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v){
openSavedSearches();
}
});
}
This is the GoogleSearch Api
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.twit_list);
txtSearch = (EditText)webView.findViewById(R.id.txtSearch);
searchbtn = (Button) webView.findViewById(R.id.searchbtn);
webView = (WebView)webView.findViewById(R.id.webView);
searchbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String item = txtSearch.getText().toString();
new JsonSearchTask(item).execute();
}
});
}
private class JsonSearchTask extends AsyncTask<Void, Void, Void> {
String searchResult = "";
String search_url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=";
String search_query;
JsonSearchTask(String item){
try {
search_item = URLEncoder.encode(item, "utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
search_query = search_url + search_item;
}
#Override
protected Void doInBackground(Void... arg0) {
try {
searchResult = ParseResult(sendQuery(search_query));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
searchbtn.setEnabled(false);
searchbtn.setText("Wait...");
super.onPreExecute();
}
#Override
protected void onPostExecute(Void result) {
webView.loadData(searchResult,
"text/html",
"UTF-8");
searchbtn.setEnabled(true);
searchbtn.setText("Search");
super.onPostExecute(result);
}
}
private String sendQuery(String query) throws IOException{
String result = "";
URL searchURL = new URL(query);
HttpURLConnection httpURLConnection = (HttpURLConnection) searchURL.openConnection();
if(httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK){
InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader,
8192);
String line = null;
while((line = bufferedReader.readLine()) != null){
result += line;
}
bufferedReader.close();
}
return result;
}
private String ParseResult(String json) throws JSONException{
String parsedResult = "";
JSONObject jsonObject = new JSONObject(json);
JSONObject jsonObject_responseData = jsonObject.getJSONObject("responseData");
JSONArray jsonArray_results = jsonObject_responseData.getJSONArray("results");
//parsedResult += "Google Search APIs (JSON) for : <b>" + search_item + "</b><br/>";
//parsedResult += "Number of results returned = <b>" + jsonArray_results.length() + "</b><br/><br/>";
for(int i = 0; i < jsonArray_results.length(); i++){
JSONObject jsonObject_i = jsonArray_results.getJSONObject(i);
String iTitle = jsonObject_i.getString("title");
String iContent = jsonObject_i.getString("content");
String iUrl = jsonObject_i.getString("url");
parsedResult += "<a href='" + iUrl + "'>" + iTitle + "</a><br/>";
parsedResult += iContent + "<br/><br/>";
}
return parsedResult;
}
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="wrap_content"
android:id = "#+id/activitymain"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id = "#+id/txtSearch"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtSearch"
android:text="Search"
android:id="#+id/searchbtn" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtSearch"
android:layout_toRightOf="#+id/searchbtn"
android:layout_toEndOf="#+id/searchbtn"
android:id="#+id/save"
android:text=" Save " />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Saved Searches"
android:id="#+id/savedSearches"
android:layout_alignTop="#+id/save"
android:layout_toRightOf="#+id/save"
android:layout_toEndOf="#+id/save" />
</RelativeLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="174dp"
android:id = "#android:id/list"
android:background="#FF498CDE">
</ListView>
<WebView
android:layout_width="match_parent"
android:layout_height="202dp"
android:id="#+id/webView"
android:layout_gravity="center_horizontal" />
Basically I want to run both api's when I click the search button.
Please someone point me in the right direction, I'm completely new to this.
Thanks
The problem is that you are not getting any response in your JsonSearchTask AsyncTask.
The problem is that the api you are using for the google web search is not available now. You should use Google Custom Search API (https://developers.google.com/custom-search/).

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.

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.

Android clickable listview

I have a android code which that get some data in json format from php file,
I successfully created a listview using those json now I want to create a second activity to show product details when I click on those items.
Here is the code :
public class MainActivity extends Activity {
private String jsonResult;
private String url = "xxxx/get_all_products.php";
private ListView listView;
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_PRICE = "price";
private static final String TAG_FOUND = "found";
private static final String TAG_DESCRIPTION = "description";
ArrayList<HashMap<String, String>> productList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView1);
productList = new ArrayList<HashMap<String, String>>();
accessWebService();
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrwaer();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[]{url});
}
// build hash set for list view
public void ListDrwaer() {
List<Map<String, String>> productList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("products");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("name");
String price = jsonChildNode.optString("price");
String found = jsonChildNode.optString("found");
// String outPut = name + "-" + number;
// String outPut = name + "-" + price + "-" + found;
// productList.add(createProduct("products", outPut));
HashMap<String, String> product = new HashMap<String, String>();
product.put(TAG_NAME, name);
product.put(TAG_FOUND, found);
product.put(TAG_PRICE, price);
productList.add(product);
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
SimpleAdapter simpleAdapter = new SimpleAdapter(this, productList,
R.layout.list_item, new String[] { TAG_NAME, TAG_PRICE,
TAG_FOUND }, new int[] { R.id.name,
R.id.price, R.id.found });
listView.setAdapter(simpleAdapter);
}
}
and also there are there are two xml layout files.
I read many examples for doing this about setOnItemClickListener whit no success.....
for example tried this with no success :
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String selval = ((TextView) view).getText().toString();
Intent intnt = new Intent(getApplicationContext(), SingleListItem.class);
intnt.putExtra("selval ", selval);
}
Here are the errors :
FATAL EXCEPTION: main
java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.widget.TextView
at sig.example.com.sig00.MainActivity$1.onItemClick(MainActivity.java:59)
Here are xml files :
<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: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=".MainActivity" >
<!-- Name Label -->
<!-- android:id="#+id/listView1" -->
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="14dp">
</ListView>
and the list_item.xml is
<?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="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp" >
<!-- Name Label -->
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:paddingTop="6dip"
android:textColor="#43bd00"
android:textSize="16sp"
android:textStyle="bold"
android:gravity="center"/>
<!-- Email label -->
<TextView
android:id="#+id/price"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="#acacac" />
<!-- Mobile number label -->
<TextView
android:id="#+id/found"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:textColor="#5d5d5d"
android:textStyle="bold" />
</LinearLayout>
Replace your code from your setOnItemClickListener() to this one :
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String selval = listview.getItemAtPosition(position).getText().toString();
// Also I've found a solution on SO that a guy solved this problem doing soemthing like this :
// TextView txt = (TextView) parent.getChildAt(position - listview.firstVisiblePosition()).findViewById(R.id.sometextview);
// String keyword = txt.getText().toString();
Intent intnt = new Intent(getApplicationContext(), SingleListItem.class);
intnt.putExtra("selval ", selval);
EDIT
Your error is that in your intent you are putting as extra "selval ", with an BLANK SPACE so if in your next activity you are doing this :
Class SingleListItem extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.productdetails);
TextView txtProduct = (TextView) findViewById(R.id.product_label);
Intent i = getIntent(); // getting attached intent data
String selval = i.getStringExtra("selval"); // displaying selected product name txtProduct.setText(selval);
}
It never will return your selval string cause you are asking for "sevlal" not from "selval ".
Just remove your unnecessary space and it will work :)
The View in onItemClick is not a TextView, it's the entire row. You should do the following
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//String selval = ((TextView) view.findViewById(R.id.yourId)).getText().toString();
HashMap<String, String> item = parent.getItemAtPosition(position);
String selval = item.get(TAG_PRICE);
Intent intnt = new Intent(getApplicationContext(), SingleListItem.class);
intnt.putExtra("selval ", selval);
}

Categories

Resources