I am trying to update the data using swipeRefreshLayout, but every time I swipe down to refresh it is only circling but not refreshing.
Can you please help me how to fix it.
package com.reader.ashishyadav271.hackernewsreader;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends Activity {
SwipeRefreshLayout mSwipeRefreshLayout;
Map<Integer, String> articleURLs = new HashMap<>();
Map<Integer, String> articleTitles = new HashMap<>();
ArrayList<Integer> articleIds = new ArrayList<>();
SQLiteDatabase articlesDB;
ArrayList<String> titles = new ArrayList<>();
ArrayAdapter arrayAdapter;
ArrayList<String> urls = new ArrayList<>();
ArrayList<String> content = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.activity_main_swipe_refresh_layout);
mSwipeRefreshLayout.setColorSchemeResources(R.color.red, R.color.green, R.color.blue, R.color.yellow);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
refreshContent();
}
});
ListView listView = (ListView) findViewById(R.id.listView);
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, titles);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(getApplicationContext(), Main2Activity.class);
i.putExtra("articleUrl", urls.get(position));
i.putExtra("content", content.get(position));
startActivity(i);
}
});
articlesDB = this.openOrCreateDatabase("Articles", MODE_PRIVATE, null);
articlesDB.execSQL("CREATE TABLE IF NOT EXISTS articles (id INTEGER PRIMARY KEY, articleId INTEGER, url VARCHAR, title VARCHAR, content VARCHAR)");
updateListView();
DownloadTask task = new DownloadTask();
try {
task.execute("https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty");
} catch (Exception e) {
e.printStackTrace();
}
}
private void refreshContent() {
arrayAdapter.notifyDataSetChanged();
titles.clear();
updateListView();
mSwipeRefreshLayout.setRefreshing(false);
}
public void updateListView() {
try {
Log.i("UI UPDATED", "DONE");
Cursor c = articlesDB.rawQuery("SELECT * FROM articles", null);
int contentIndex = c.getColumnIndex("content");
int urlIndex = c.getColumnIndex("url");
int titleIndex = c.getColumnIndex("title");
c.moveToFirst();
titles.clear();
urls.clear();
while (c != null) {
titles.add(c.getString(titleIndex));
urls.add(c.getString(urlIndex));
content.add(c.getString(contentIndex));
c.moveToNext();
}
arrayAdapter.notifyDataSetChanged();
}catch (Exception e) {
e.printStackTrace();
}
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
JSONArray jsonArray = new JSONArray(result);
articlesDB.execSQL("DELETE FROM articles");
for (int i = 0; i < 20; i++) {
String articleId = jsonArray.getString(i);
url = new URL("https://hacker-news.firebaseio.com/v0/item/" + articleId + ".json?print=pretty");
urlConnection = (HttpURLConnection) url.openConnection();
in = urlConnection.getInputStream();
reader = new InputStreamReader(in);
data = reader.read();
String articleInfo = "";
while (data != -1 ) {
char current = (char) data;
articleInfo += current;
data = reader.read();
}
JSONObject jsonObject = new JSONObject(articleInfo);
String articleTitle = jsonObject.getString("title");
String articleURL = jsonObject.getString("url");
String articleContent = "";
/*
url = new URL(articleURL);
urlConnection = (HttpURLConnection) url.openConnection();
in = urlConnection.getInputStream();
reader = new InputStreamReader(in);
data = reader.read();
while (data != -1 ) {
char current = (char) data;
articleInfo += current;
data = reader.read();
}
*/
articleIds.add(Integer.valueOf(articleId));
articleTitles.put(Integer.valueOf(articleId), articleTitle);
articleURLs.put(Integer.valueOf(articleId), articleURL);
String sql = "INSERT INTO articles (articleId, url, title, content) VALUES (? , ? , ? , ?)";
SQLiteStatement statement = articlesDB.compileStatement(sql);
statement.bindString(1, articleId);
statement.bindString(2, articleURL);
statement.bindString(3, articleTitle);
statement.bindString(4, articleContent);
statement.execute();
}
}catch (Exception e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
refreshContent();
}
}
}
It look like synchronism problem. I can see you load data from DownloadTask and put all of data to database. RefreshMethod query data from database.
I assume if DownloadTask do not finish yet, database isn't updated and RefreshMethod would get nothing from database. So, It is only circling but not refreshing.
To solve synchronism problem, the right application flow should be: Raise PullToRefresh Event -> execute DownloadTask -> Wait until DownloadTask finish, RefreshMethod query database for data.
Code looks like:
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
DownloadTask task = new DownloadTask();
try {
task.execute("https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty");
} catch (Exception e) {
e.printStackTrace();
}
}
});
Related
I want to show list of data seperated by pages that is first i want to show 5 details and then when user scrolls down then it loads 5 more by again calling the api now i have been able to show first 5 details but when scrolling it replaces previous 5 with new 5 details it is not adding data instead replacing it.
MainFile in which i want to show the data
package com.example.vinod.lcoportal;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
/**
* A simple {#link Fragment} subclass.
*/
public class StbDetailsFragment extends Fragment {
RecyclerView recycler_view_stb_details;
ArrayList<StbDetails> listitems_stb = new ArrayList<>();
String[] name = new String[50];
String[] address = new String[100];
String[] vc_stb = new String[100];
String[] city = new String[100];
String[] current_plan = new String[200];
String[] status = new String[50];
String[] csi = new String[300];
int currentpage = 0;
int pagesize = 5;
ProgressDialog pDialog;
JSONArray ja;
JSONObject jo;
String custcsi, custcity, custname, currentplan, custstatus, vc_no;
String stb_url = "http://lco.denonline.in/wapp/Service1.svc/Dashboard";
public StbDetailsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_stb_details, container, false);
currentpage = currentpage + 1;
GetStb getStb= new GetStb(currentpage, pagesize);
getStb.execute(stb_url);
return view;
}
public class MyAdapterStb extends RecyclerView.Adapter<MyAdapterStb.MyViewHolderStb> {
private ArrayList<StbDetails> list;
public MyAdapterStb(ArrayList<StbDetails> Data) {
list = Data;
}
#Override
public MyViewHolderStb onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.stb_details_cardview, parent, false);
MyViewHolderStb holder = new MyViewHolderStb(view);
return holder;
}
#Override
public void onBindViewHolder(final MyViewHolderStb holder, int position) {
holder.cust_name.setText(list.get(position).getName());
holder.cust_address.setText(list.get(position).getAddress());
holder.cust_vc.setText(list.get(position).getVc_stb_no());
holder.cust_city.setText(list.get(position).getCity());
holder.cust_plan.setText(list.get(position).getCurrentPlan());
holder.cust_status.setText(list.get(position).getStatus());
// holder.events_imageview.setImageResource(list.get(position).getImageResourceId());
// holder.events_imageview.setTag(list.get(position).getImageResourceId());
// Glide.with(getActivity()).load(list.get(position).getImageResourceId_notices()).into(holder.notices_imageview);
}
#Override
public int getItemCount() {
return list.size();
}
public class MyViewHolderStb extends RecyclerView.ViewHolder {
TextView cust_name, cust_address, cust_vc, cust_city, cust_plan, cust_status ;
public MyViewHolderStb(View v) {
super(v);
cust_name = (TextView) v.findViewById(R.id.name_stb_details);
cust_address = (TextView) v.findViewById(R.id.address_stb_details);
cust_vc = (TextView) v.findViewById(R.id.vc_stb_no_stb_details);
cust_city = (TextView) v.findViewById(R.id.city_stb_details);
cust_plan = (TextView) v.findViewById(R.id.current_plan_stb_details);
cust_status = (TextView) v.findViewById(R.id.status_stb_details);
// v.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// Intent i = new Intent(getActivity(),NoticesViewActivity.class);
// i.putExtra("notice_url",pdf[getAdapterPosition()]);
// i.putExtra("notice_title",title_notices[getAdapterPosition()]);
// startActivity(i);
// }
// });
}
}
}
public void initializeList() {
listitems_stb.clear();
for (int i = 0; i < ja.length(); i++) {
StbDetails item = new StbDetails();
item.setName(name[i]);
item.setAddress(address[i]);
item.setVc_stb_no(vc_stb[i]);
item.setCity(city[i]);
item.setCurrentPlan(current_plan[i]);
item.setStatus(status[i]);
listitems_stb.add(item);
}
}
public class GetStb extends AsyncTask<String,String,String> {
HttpURLConnection httpURLConnection;
int CurrentPage, PageSize;
public GetStb(int currentpage, int pagesize) {
CurrentPage = currentpage;
PageSize = pagesize;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Fetching Data...Please Wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//pDialog.show();
// progress_dialog.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... params) {
try {
URL url = new URL(params[0]);
Log.d("DoInBackground:URL", url.toString());
//Send Post Data request
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.addRequestProperty("api_key", "XBoGycClZkJrXDVphgpN5c9Bb82fcKQ4");
httpURLConnection.addRequestProperty("gulco", "fe96632f-5173-e611-942d-005056bb1e58");
httpURLConnection.addRequestProperty("currentpage", String.valueOf(CurrentPage));
httpURLConnection.addRequestProperty("pagesize", String.valueOf(PageSize));
//)httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setDoInput(true);
httpURLConnection.connect();
//Get the Server Response
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String response = "";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
response += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
Log.d("DoInBackground", "Response:" + response);
return response;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String response) {
GridLayoutManager MyLayoutManager = new GridLayoutManager(getActivity(),1);
MyLayoutManager.setOrientation(GridLayoutManager.VERTICAL);
recycler_view_stb_details = (RecyclerView) getActivity().findViewById(R.id.recycler_view_stb_details);
recycler_view_stb_details.setHasFixedSize(true);
try {
ja = new JSONArray(response);
//ja = jo.getJSONArray("notices");
//images = new String[ja.length()];
//title = new String[ja.length()];
for (int i=0;i<ja.length();i++) {
JSONObject json = ja.getJSONObject(i);
custcsi = json.getString("CSI");
custcity = json.getString("City");
custname = json.getString("CustName");
currentplan = json.getString("Plan");
custstatus = json.getString("Status");
vc_no = json.getString("VCNO");
name[i] = custname;
csi[i] = custcsi;
city[i] = custcity;
current_plan[i] = currentplan;
vc_stb[i] = vc_no;
status[i] = custstatus;
initializeList();
}
} catch (Exception e) {
e.printStackTrace();
}
//progress_dialog.setVisibility(View.GONE);
//pDialog.dismiss();
if (listitems_stb.size() > 0 & recycler_view_stb_details != null) {
recycler_view_stb_details.setAdapter(new MyAdapterStb(listitems_stb));
}
recycler_view_stb_details.setLayoutManager(MyLayoutManager);
//pDialog.dismiss();
}
}
}
I think your problem is that every time in the public void initializeList() you call first of all listitems_stb.clear(); so your list will be cleared every time and you will lose all the previous data.
So if you wanna add other elements to the list you shouldn't clear it. Just try to delete listitems_stb.clear();.
Then for pagination see this answer here.
Hope this helps
I recently started learning JSON to use in my apps. I found a weather API (openweathermap.org) and used it on my app. the app runs fine but when I press Button, nothing happens. my source code:
import android.content.Context;
import android.hardware.input.InputManager;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.*;
import java.net.*;
import java.util.*;
import android.util.*;
import android.view.*;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import org.json.*;
public class MainActivity extends AppCompatActivity {
EditText city;
TextView weather, description;
DownloadTask DownloadTask;
public void showWeather (View view)
{
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(city.getWindowToken(), 0);
try
{
String encodedCityName = URLEncoder.encode(city.getText().toString(), "UTF-8");
DownloadTask = new DownloadTask();
DownloadTask.execute("http://api.openweathermap.org/data/2.5/weather?q=" + encodedCityName + "&appid=812f300ec742971975bbde9a2e0ac0c1");
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Error!", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
city = (EditText) findViewById(R.id.city);
weather = (TextView) findViewById(R.id.weather);
description = (TextView) findViewById(R.id.description);
}
public class DownloadTask extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection connection = null;
try
{
url = new URL(urls[0]);
connection = (HttpURLConnection) url.openConnection();
InputStream in = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != 1)
{
char current = (char) data;
result += current;
data = reader.read();
}
return result;
}
catch (Exception e)
{
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Error!", Toast.LENGTH_LONG);
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.i("Weather content", result);
try
{
JSONObject jsonObject = new JSONObject(result);
String weatherInfo = jsonObject.getString("weather");
Log.i("Weather Content", weatherInfo);
JSONArray jsonArray = new JSONArray(weatherInfo);
String getMain = "";
String getDescription = "";
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject jsonPart = jsonArray.getJSONObject(i);
getMain = jsonPart.getString("main");
getDescription = jsonPart.getString("description");
Log.i("Main", getMain);
}
if (getMain != "" && getDescription != "")
{
weather.setText(getMain);
description.setText(getDescription);
}
}
catch (JSONException e)
{
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Error!", Toast.LENGTH_LONG);
}
}
}
}
none of Toasts and Logs work.
You have an error in reading the data. You should stop reading when getting -1 not 1.
while (data != -1)
{
char current = (char) data;
result += current;
data = reader.read();
}
I'm developing an app and now I have to pass a parameter to a RESTful Service's URL. I'm using AsyncTask, and I need to pass a text from a list view as a parameter to the URL, for example: the URL is http://ip:7001/product?product_name=PARAM I need to get the text from the selected item from my list view, and pass as a parameter in PARAM, using AsyncTask. I've already got the text from the item in the listView, now I just need to pass it as a parameter.
This is my AsycTask class:
package com.tumta.henrique.teste;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import com.tumta.henrique.teste.ProdutoFragment;
/**
* Created by Henrique on 18/05/2015.
*/
public class FiltraProduto extends AsyncTask<String, Void, List<String>> {
private ConsultaConcluidaFiltroProdutoListener listener;
public static String URL_STRING = "http://192.168.0.20:7001/com.henrique.rest/api/v1/status/pro_filtro?pro_nome=";
public FiltraProduto(ConsultaConcluidaFiltroProdutoListener listener) {
this.listener = listener;
}
private List<String> InterpretaResultado(String resultado) throws JSONException {
JSONObject object = new JSONObject(resultado);
JSONArray jsonArray = object.getJSONArray("produto");
//JSONObject jsonProduto = jsonArray.getJSONObject(0);
// String id = jsonProduto.getString("pro_id");
//proId = id;
List<Object> listaNomes = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonProdutoInfo = jsonArray.getJSONObject(i);
String proNome= jsonProdutoInfo.getString("pro_nome");
double proPreco = jsonProdutoInfo.getDouble("pro_preco");
double proSdAtual = jsonProdutoInfo.getDouble("pro_sdAtual");
listaNomes.add(i, proNome);
listaNomes.add(i, proPreco);
listaNomes.add(i, proSdAtual);
}
List<String> strings = new ArrayList<String>();
for (Object o : listaNomes) {
strings.add(o != null ? o.toString() : null);
}
return strings;
}
private String ConsultaServidor() throws IOException {
InputStream is = null;
try {
URL url = new URL(URL_STRING);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(10000);
conn.setReadTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
conn.getResponseCode();
is = conn.getInputStream();
Reader reader = null;
reader = new InputStreamReader(is);
char[] buffer = new char[2048];
reader.read(buffer);
return new String(buffer);
} finally {
if (is != null) {
is.close();
}
}
}
#Override
protected List<String> doInBackground(String... params) {
try {
String resultado = ConsultaServidor();
return InterpretaResultado(resultado);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(List<String> result) {
listener.onConsultaConcluida(result);
super.onPostExecute(result);
}
public interface ConsultaConcluidaFiltroProdutoListener {
void onConsultaConcluida(List<String> result);
}
}
In the URL_STRING I need to pass the param at pro_nome=?
Here I get the item text. This is in my Fragment that has the List View:
public String retornaParam(String param){
return param;
}
#Override
public void onConsultaConcluida(List<String> result) {
final ListView listaProdutos = (ListView) getView().findViewById(R.id.listaprodutos);
ArrayAdapter arrayAdapter = new ArrayAdapter<>(getView().getContext(),android.R.layout.simple_list_item_1, result);
listaProdutos.setAdapter(arrayAdapter);
listaProdutos.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parentAdapter, View view, int position,
long id) {
String nomeProduto = listaProdutos.getItemAtPosition(position).toString();
retornaParam(nomeProduto);
Intent intent = new Intent(getActivity(), DetalhesProdutoActivity.class);
//intent.putExtra("pro_nome", listaProdutos.getItemAtPosition(position).toString());
startActivity(intent);
}
});
}
I get the text and store it in param from the retornaParam method.
Does somebody know how to do it?
If you need more information, just let me know.
You pass in params to an AsyncTask using:
YourAsyncTask.execute(yourview.getText(), "and", "more", "params");
You can then access them in
#Override
protected String doInBackground(String... params) {
URL_STRING += params[0];
...
Just add the following code before sending executing your httpClient:
URL_STRING + = textInsideYourTextView;
It should work, just avoid to manipulate your ui elements outside your UI thread.
I have a form having one edittext and an autocompleteview. And a button to search things based on this form. In this form I can either give value in edittext and autocompleteview may be empty and vice versa. On this basis I have passed value of these view to another activity where I made a webservice call and then fetch result.
This is activity where these view are presents:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_patient_section);
getSupportActionBar().hide();
searchByNameEditText = (EditText) findViewById(R.id.searchByNameEditText);
searchByAddressEditText = (EditText) findViewById(R.id.searchByAddressEditText);
searchButton = (Button) findViewById(R.id.searchButton);
autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.selectStateSpinner);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_dropdown_item_1line,
getResources().getStringArray(R.array.state_arrays));
autoCompleteTextView.setAdapter(adapter);
patientUtilityButton = (Button) findViewById(R.id.patientUtilityButton);
patientUtilityButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(PatientSectionActivity.this, patientUtilityButton);
popupMenu.getMenuInflater().inflate(R.menu.patient_utility_button_popmenu, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
String patientUtilityMenuItem = item.toString();
patientUtilityButton.setText(patientUtilityMenuItem);
return true;
}
});
popupMenu.show();
}
});
autoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectedStateValue = (String) parent.getItemAtPosition(position);
}
});
doctorName = searchByNameEditText.getText().toString();
// Search Button
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!selectedStateValue.equals(" ") || doctorName.equals(" ")){
Intent intent = new Intent(PatientSectionActivity.this, DoctorNameActivity.class);
intent.putExtra("State Name", selectedStateValue);
startActivity(intent);
} else if (!doctorName.equals(" ") || selectedStateValue.equals(" ")){
Intent intent = new Intent(PatientSectionActivity.this, DoctorNameActivity.class);
intent.putExtra("Name", doctorName);
startActivity(intent);
}
}
});
}
And in other activity, I get these extras from intent and make webservice call in AsyncTask but my app is crashing. Please any one help me as I am new in android.
This is my other activity
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class DoctorNameActivity extends ActionBarActivity {
ArrayAdapter<String> doctorAdapter;
ListView listView;
ProgressBar progressBar;
String doctorName;
String selectedStateValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doctor_name);
progressBar = (ProgressBar) findViewById(R.id.progress);
listView = (ListView) findViewById(R.id.listView);
Intent intent = getIntent();
selectedStateValue = intent.getStringExtra("State Name");
doctorName = intent.getStringExtra("Name");
if (!selectedStateValue.equals(" ") || doctorName.equals(" ")){
FetchDoctorName fetchDoctorName = new FetchDoctorName();
fetchDoctorName.execute(selectedStateValue);
}else if (!doctorName.equals(" ") || selectedStateValue.equals(" ")){
FetchDoctorName fetchDoctorName = new FetchDoctorName();
fetchDoctorName.execute(doctorName);
}
}
private class FetchDoctorName extends AsyncTask<String, Void, String[]>{
private final String LOG_TAG = FetchDoctorName.class.getSimpleName();
public String[] parseDoctorName(String jsonString) throws JSONException{
final String DOCTOR_NAME_ARRAY = "name";
JSONObject object = new JSONObject(jsonString);
JSONArray array = object.getJSONArray(DOCTOR_NAME_ARRAY);
String[] doctorNamesResult = new String[array.length()];
for (int i = 0 ; i < array.length(); i++){
String doctorName = array.getString(i);
Log.v(LOG_TAG, doctorName);
doctorNamesResult[i] = doctorName;
}
return doctorNamesResult;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(ProgressBar.VISIBLE);
}
#Override
protected String[] doInBackground(String... params) {
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String doctorJsonString = null;
try {
final String BASE_URL = "http://mycityortho.com/display_result.php";
final String NAME_PARAM = "name";
final String STATE_PARAM = "state";
URL url = null;
if (params[0].equals(doctorName)){
Uri uri = Uri.parse(BASE_URL).buildUpon()
.appendQueryParameter(NAME_PARAM, params[0])
.build();
url = new URL(uri.toString());
Log.v(LOG_TAG, url.toString());
}else if (params[0].equals(selectedStateValue)){
Uri uri = Uri.parse(BASE_URL).buildUpon()
.appendQueryParameter(STATE_PARAM, params[0])
.build();
url = new URL(uri.toString());
Log.v(LOG_TAG, url.toString());
}
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
doctorJsonString = buffer.toString();
Log.v(LOG_TAG, doctorJsonString);
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
try {
return parseDoctorName(doctorJsonString);
}catch (JSONException e){
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String[] result) {
progressBar.setVisibility(ProgressBar.GONE);
if (result != null){
doctorAdapter = new ArrayAdapter<>(DoctorNameActivity.this, android.R.layout.simple_list_item_1, result);
listView.setAdapter(doctorAdapter);
}
}
}
As per your code you are sending only one value in intent that is "State Name" or "Name" but in other activity you are trying to receive both value, that why you get null pointer exception.
So use the following code to solve this error.
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!selectedStateValue.equals(" ") || doctorName.equals(" ")){
Intent intent = new Intent(PatientSectionActivity.this, DoctorNameActivity.class);
intent.putExtra("State Name", selectedStateValue);
intent.putExtra("Name", " ");
startActivity(intent);
} else if (!doctorName.equals(" ") || selectedStateValue.equals(" ")){
Intent intent = new Intent(PatientSectionActivity.this, DoctorNameActivity.class);
intent.putExtra("State Name", " ");
intent.putExtra("Name", doctorName);
startActivity(intent);
}
}
});
I have a listview now i need to pass the listview data to a another activity how do i do it ?
MainActivity
package learn2crack.listview;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import java.util.List;
import android.view.Menu;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import learn2crack.listview.library.JSONParser;
public class MainActivity extends Activity {
ListView list;
TextView ver;
TextView name;
TextView api;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
private static String url = "http://216.185.116.35/LOGISTIC/WebServices/json/getDeliveriItems_bak.ashx?id=485";
private static final String TAG_OS = "android";
private static final String TAG_VER = "BagNumber";
private static final String TAG_NAME = "COD";
private static final String TAG_API = "OrderNo";
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oslist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
ver = (TextView)findViewById(R.id.vers);
name = (TextView)findViewById(R.id.name);
api = (TextView)findViewById(R.id.api);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
String ver = c.getString(TAG_VER);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_API);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_VER, ver);
map.put(TAG_NAME, name);
map.put(TAG_API, api);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
listAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,R.layout.list_v,new String[] { TAG_VER,TAG_NAME, TAG_API }, new int[] {
R.id.vers,R.id.name, R.id.api});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
JSONParser.java
package learn2crack.listview.library;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
json = sb.toString();
json = "{ \"android\":"+json+"}";
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
}
I have found some explanation how to pass data but I am having problem at new AdapterView.OnItemClickListener()
The problem is
oslist.get(+position)
should be
oslist.get(position)
Also you have
private static final String TAG_NAME = "COD"; // key for name is COD
map.put(TAG_NAME, name);
then
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String name = oslist.get(position).get("COD");
Intent intent = new Intent(ActivityName.this, YOURACTIVITY.class);
intent.putExtra("key", name);
startActivity(intent);
}
});
Should move setAdapter coe out of for loop
Also change to
#Override
protected void onPostExecute(JSONObject json) {
super.onPostExecute(json);
pDialog.dismiss();
try {
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
String ver = c.getString(TAG_VER);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_API);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_VER, ver);
map.put(TAG_NAME, name);
map.put(TAG_API, api);
oslist.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
list=(ListView)findViewById(R.id.list);
listAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,R.layout.list_v,new String[] { TAG_VER,TAG_NAME, TAG_API }, new int[] {
R.id.vers,R.id.name, R.id.api});
list.setAdapter(adapter)
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String name = oslist.get(position).get("COD");
String ver = oslist.get(position).get(TAG_VER);
String api = oslist.get(position).get(TAG_API);
Intent intent = new Intent(MainActivity.this, AnotherActivity.class);
intent.putExtra("key", name);
intent.putExtra("key1", ver);
intent.putExtra("key2", api);
startActivity(intent);
}
});
}
In Another Activtiy
String name =getIntent().getStringExtra("key");
String api =getIntent().getStringExtra("key1");
String ver =getIntent().getStringExtra("key"2);
You should create a custom adapter. Also create a DataModel which will hold all the 3 values (Version, Name and Api). Make it Serializable.
public class MyModel implements Serializable{
private static final long serialVersionUID = 1L;
String version, name, api;
public MyModel(String modelVer, String modelName, String modelApi){
version = modelVer;
name = modelName ;
api = modelApi;
}
//Add Getters and Setters
}
Instead of creating HashMap<String, String> map = new HashMap<String, String>(); Create
ArrayList<MyModel> modelList = new ArrayList<MyModel>();
then in OnItemClickListener()
//To send data
MyModel modelToPass = modelList.get(position);
intent.putExtra("MyObject", modelToPass);
//To get data
getIntent().getSerializableExtra("MyObject");
for example you can pass the position of item that is clicked by below code
public void onListItemClick(ListView parent, View v, int position,
long id){
Intent intent = new Intent(getApplicationContext(), YourActivity.class);
intent.putExtra("pos", position);
startActivity(intent);
}
in YourActivity oncreate() method
Intent current=getIntent();
int position=current.getExtras().getInt("pos");
for sending your data you can make class below
public class Information implements Serializable {
public String BagNumber;
public String COD;
public String OrderNo;
public String SubOrderNo;
......
......
}
and for send it
Information details = new Information ();
details.BagNumber = "";
details.COD = "12";
details.OrderNo = "ff";
....
....
Intent i = new Intent(getApplicationContext(), YourActivity.class);
i.putExtra("inf", details);
startActivity(i);
For receive it
Information model = (Information ) getIntent().getSerializableExtra("inf");