I tried many ways but I got blank layout.I changed lots of lines but the result is always the same. Should I rewrite the code and try something different. I followed some videos on youtube but nobody has the proper solution.I don't think it is caused because array got null result. Anybody knows what might be wrong:
AirportTransportActivity
public class AirportTransportActivity extends AppCompatActivity {
ListView listView;
ArrayAdapter<String> adapter;
String[] data = new String[0];
JSONObject jsonObject = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_airport_transport);
//Get airport details
Intent intent = getIntent();
String getairport = intent.getStringExtra("airport");
final TextView textViewAirport = (TextView) findViewById(R.id.tvairport);
textViewAirport.setText(getairport);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
//List view setup
listView = (ListView) findViewById(R.id.lvairport);
//Get airport transport
new RetrieveTask().execute();
//Adapter
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
listView.setAdapter(adapter);
}
private class RetrieveTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... voids) {
String strUrl = "http://my database";
URL url = null;
StringBuffer sb = new StringBuffer();
try {
url = new URL(strUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream iStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(iStream));
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
iStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
#Override
protected void onPostExecute(String result) {
try {
JSONArray jsonArray = new JSONArray(result);
data = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
data[i] = jsonObject.getString("airporttransportname");
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}
}
In your original post you have set the adapter before you have added the data. But I also suspect that you are having issues with:
String[] data = new String[0];
So I changed it to
ArrayList<String> data = new ArrayList<>();
I also changed your AsyncTask a bit. Now you can do most of your parsing in the background thread. When the doInBackground is successful just notify the adapter of the changes in onPostExecute.
You will also need to check if the ArrayList<String> fits to your Adapter class. If not just change it as needed.
Do this instead:
public class AirportTransportActivity extends AppCompatActivity {
private static final String TAG = AirportTransportActivity.class.getSimpleName();
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_airport_transport);
//Get airport details
Intent intent = getIntent();
String getairport = intent.getStringExtra("airport");
final TextView textViewAirport = (TextView) findViewById(R.id.tvairport);
textViewAirport.setText(getairport);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
//List view setup
listView = (ListView) findViewById(R.id.lvairport);
//Get airport transport
new RetrieveTask().execute();
}
private class RetrieveTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... voids) {
String strUrl = "http://my database";
URL url = null;
StringBuffer sb = new StringBuffer();
try {
url = new URL(strUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream iStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(iStream));
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
iStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return toString();
}
#Override
protected void onPostExecute(String result) {
if(result.isEmpty()) return;
try{
ArrayList<String> data = new ArrayList<>();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
JSONArray jsonArray = new JSONArray(result);
int len = jsonArray.length();
Log.e(TAG, "Lenth of json array = " + len)
for (int i = 0; i < len; i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// I add the optString variation just in case the data is corrupt
String s = jsonObject.optString("airporttransportname", "?");
data.add(s);
}
listView.setAdapter(adapter);
}
catch(JSONException e){
e.printStackTrace();
}
}
}
Disclaimer I did this in a text editor and wasn't able to count on "auto-correct" for some of the syntax or method names--so you will need to check it.
There are some other things I would change in your code, but I wanted to leave it as close to the original as I could.
You're setting the data array and calling notifyDataSetChanged() before your async task has a chance to finish. You need to set your adapter and notifyDataSetChanged() from within the onPostExecute() method in your async task.
Just to be clear, when you call asyncTask.execute(), it starts the async task and then immediately keeps executing the rest of the code. So when you set your data array in your list view adapter, the asyncTask hasn't even finished and your array items are still null.
No need to change anything just add adapter.notifyDataSetChanged(); after storing all values into your array
Remove this line adapter.notifyDataSetChanged();in Oncreate ,You
have to use notifyDataSetChanged() when your arraylist values is getting
changed.
#Override
protected void onPostExecute(String result) {
try {
JSONArray jsonArray = new JSONArray(result);
data = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
data[i] = jsonObject.getString("airporttransportname");
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
Related
I'm writing a simple Android app to get a JSON array into RecyclerView with AsyncTask. I know that I can use libraries as Retrofit or OKHTTP, but this time I tried to write the connection IO from scratch. The connection succeeded and data has been parsed and added to ArrayList. I do all of these in doInBackground(), and in onPostExecute() I just call notifyDataSetChanged() to the adapter, but it didn't work. I tried several ways such as move setAdapter() to onPostExecute(), or move all the AsyncTask to Adapter class and they didn't help anything. Can someone tell me what I miss, if I cannot fix it in 2 or 3 days, I think I will use Retrofit instead.
This is my Main class, I think the bug is only here, but if you need to see my adapter please leave a comment, thanks a lot.
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
ProgressDialog progressDialog;
String apiUrl;
Gson gson;
List<User> userList;
UserAdapter userAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycle_view);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
apiUrl = "https://lebavui.github.io/jsons/users.json";
gson = new Gson();
userList = new ArrayList<>();
userAdapter = new UserAdapter(userList, MainActivity.this);
recyclerView.setAdapter(userAdapter);
DataGetter dataGetter = new DataGetter();
dataGetter.execute();
}
private class DataGetter extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... voids) {
StringBuilder response = new StringBuilder();
URL url;
HttpsURLConnection urlConnection = null;
try {
url = new URL(apiUrl);
urlConnection = (HttpsURLConnection) url.openConnection();
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int data = isr.read();
while (data != -1) {
response.append((char) data);
data = isr.read();
}
JSONArray jsonArray = new JSONArray(response.toString());
for (int i = 0; i < jsonArray.length(); i++) {
userList.add(gson.fromJson(jsonArray.getJSONObject(i).toString(), User.class));
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
#SuppressLint("NotifyDataSetChanged")
#Override
protected void onPostExecute(Void unused) {
super.onPostExecute(unused);
progressDialog.dismiss();
userAdapter.notifyDataSetChanged();
}
}
}
As mentioned in comments you should be using something other than depreciated classes. Below is an example of using runnable, simply add your parser and adapter
This should be moved to android view model.
public class MainActivity extends AppCompatActivity {
private final String LOG_TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.v(LOG_TAG, "on Create");
String apiUrl = "https://lebavui.github.io/jsons/users.json";
getUsers(apiUrl);
}
//return interface
public interface Completion{
void onCompletion(List<String> list);
}
//calls a function which call Completion.onCompletion interface off of main thread
public void getUsers(String apiUrl){
getAsyncData(apiUrl, this::setListDataOnMain);
}
//bring back to main thread
//This should be in Android View model for application context instead of this.getMainLooper
private void setListDataOnMain(List<String> list){
Handler mainHandler = new Handler(this.getMainLooper());
Runnable myRunnable = () -> {
//Set local object "list" to your global variable
//Then notify adapter change
//only logging here as example
Log.v(LOG_TAG, "List: " + list);
};
mainHandler.post(myRunnable);
}
//make async
public void getAsyncData(String apiUrl, Completion completion) {
Runnable runnable = () -> {
List<String> userList = makeRequest(apiUrl);
completion.onCompletion(userList);
};
Thread thread = new Thread(runnable);
thread.start();
}
//This is not async calling this func from main thread will crash
public List<String> makeRequest(String apiUrl ) {
List<String> userList = new ArrayList<>();
StringBuilder response = new StringBuilder();
URL url;
HttpsURLConnection urlConnection = null;
try {
url = new URL(apiUrl);
urlConnection = (HttpsURLConnection) url.openConnection();
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int data = isr.read();
while (data != -1) {
response.append((char) data);
data = isr.read();
}
JSONArray jsonArray = new JSONArray(response.toString());
for (int i = 0; i < jsonArray.length(); i++) {
//your json parsing here
userList.add(String.valueOf(i));
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return userList;
}
}
I think the DataGetter class need to executed first than you can set adapter
i test this code and it works
#SuppressLint("NotifyDataSetChanged")
#Override
protected void onPostExecute(Void unused) {
super.onPostExecute(unused);
progressDialog.dismiss();
userAdapter = new UserAdapter(userList, MainActivity.this);
recyclerView.setAdapter(userAdapter);
}
I have an app that is supposed to read a json file and inset its contents into a list view, I know this question was asked tons of times here but I can't understand why it's not working. I managed to narrow my problem to 1 line so far, JSONObject object = new JSONObject(readJSON());. This is all of my code:
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayList<Post> arrayList;
private static final String TAG = "MyActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.lvPosts);
arrayList = new ArrayList<>();
try {
JSONObject object = new JSONObject(readJSON());
JSONArray array = object.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
String productName = jsonObject.getString("productName");
String locationName = jsonObject.getString("locationName");
String price = jsonObject.getString("price");
String date = jsonObject.getString("date");
String description = jsonObject.getString("description");
String comment = jsonObject.getString("comment");
Log.i(TAG, price);
Post post = new Post();
post.setItemName(productName);
post.setLocationName(locationName);
post.setPrice(price);
post.setDate(date);
post.setDescription(description);
post.setExistingComment(comment);
arrayList.add(post);
}
} catch (JSONException e) {
e.printStackTrace();
}
PostAdapter adapter = new PostAdapter(this, arrayList);
listView.setAdapter(adapter);
}
public String readJSON() {
String json = null;
try {
// Opening data.json file
InputStream inputStream = getAssets().open("MOCK_DATA.json");
int size = inputStream.available();
byte[] buffer = new byte[size];
// read values in the byte array
inputStream.read(buffer);
inputStream.close();
// convert byte to string
json = new String(buffer, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
return null;
}
return json;
}
}
My problem is that once I run the app my listView will remain empty and wont be populated with data.
if you are using java version >jdk1.7 then I would recommend you use Files class from "java.nio.file" package . you can easily read JSON file in a single line code.
public String readJSON() {
String jsontext="";
try{
jsontext= new String(Files.readAllBytes(Paths.get("<file path>"),StandardCharset.UTF_8);
}
catch(Exception ex){
ex.printStackTrace();
}
return jsontext;
}
after that you can use JSONObject to parse string like below:---
JSONObject object = new JSONObject(readJSON());
I'm reading some text from HttpUrlConnection request and putting it in ArrayList every iteration of a loop.
All works perfect, except items in ListView don't updating in UI after every iteration of a loop (only at the end).
I'm tried next 4 methods: arrayAdapter.notifyDataSetChanged(), listView.invalidateViews(), runOnUiThread(), onPostExecute() nothing helps.
Here is my code:
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayList<String> news = new ArrayList<>();
ArrayList<String> headers = new ArrayList<>();
ArrayAdapter<String> arrayAdapter;
static JSONArray array;
NewsUnpacker unpacker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
String link = "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty";
NewsLoader newsLoader = new NewsLoader();
array = null;
try {
array = newsLoader.execute(link).get();
} catch (Exception e) {
e.printStackTrace();
}
arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, headers);
listView.setAdapter(arrayAdapter);
final int size = 15;
for (int i = 0; i < size; i++) {
try {
unpacker = new NewsUnpacker(this);
String info = unpacker.execute("https://hacker-news.firebaseio.com/v0/item/" + array.get(i) + ".json?print=pretty").get();
if (info == null) {
unpacker.cancel(true);
return;
}
news.add(info);
headers.add(info.split(System.lineSeparator())[0]);
arrayAdapter.notifyDataSetChanged();
listView.invalidateViews();
unpacker.cancel(true);
} catch (Exception e) {
e.printStackTrace();
}
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
}
static class NewsUnpacker extends AsyncTask<String, Void, String> {
MainActivity activity;
NewsUnpacker(MainActivity activity) {
this.activity = activity;
}
#Override
protected String doInBackground(String... urls) {
String info = null;
try {
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream is = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(is);
StringBuilder builder = new StringBuilder();
int data;
while ((data = reader.read()) != -1)
builder.append((char) data);
String title, urlParam;
JSONObject object = new JSONObject(builder.toString());
title = object.get("title").toString();
urlParam = object.get("url").toString();
info = title + System.lineSeparator() + urlParam;
System.out.println(info);
} catch (Exception e) {
e.printStackTrace();
}
return info;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
static class NewsLoader extends AsyncTask<String, Void, JSONArray> {
JSONArray array = null;
#Override
protected JSONArray doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream is = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(is);
StringBuilder builder = new StringBuilder();
int data;
while ((data = reader.read()) != -1)
builder.append((char) data);
array = new JSONArray(builder.toString());
} catch (Exception e) {
e.printStackTrace();
}
return array;
}
}
}
I am New to the android studio and want to something more. Actually, I am trying to pass the string that I got from the spinner in onCreateMethod and pass to the onPostExecute function. I will be grateful for the help. Bellow is my code.
I tried making a global variable called First and store the string from spinner and pass it on the onPostExecute function.
public class Convert extends AppCompatActivity implements LocationListener
{
Spinner dropdown;
Button btn;
String text;
String first;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_convert);
dropdown = (Spinner) findViewById(R.id.spinner1);
btn = (Button)findViewById(R.id.btn);
String[] items = new String[]{"United States,USD", "Nepal,NPR", "Bangladesh,BDT","Brazil,BRL"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, items);
dropdown.setAdapter(adapter);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
text = dropdown.getSelectedItem().toString();
first = text.substring(text.length()-3);
Log.i("her", first);
}
});
new DownloadTask().execute("http://openexchangerates.org/api/latest.json?
app_id=XXXXXXXXXX");
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection httpURLConnection = null;
try {
url = new URL(urls[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream in = httpURLConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char counter = (char) data;
result += counter;
data = reader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try{
JSONObject jsonObject = new JSONObject(result);
JSONObject curr = jsonObject.getJSONObject("rates");
String npr = curr.getString(first);
Log.i("money", npr );
} catch (JSONException e) {
e.printStackTrace();
}
}
}
What I want is to pass the string first on the onPostExecute function.
When you will call your DownloadTask, asyncTask fires with method execute, just pass param though him. Example:
How to pass url
new DownloadTask().execute("url for download");
How to receive url
protected String doInBackground(String... urls) {
String url = urls[0]; // url for download
}
Also you could send and array of params. Also be careful with AsyncTask, do not pass your context/view variable, it could arise memory leaks, read docs.
this is my listview where data is coming from the remote server in the JSON format so everything is working fine but now I have to pass a certain value to the server and then make a filter based on that value and then load only the desired result into the listview
public class Reciepe extends AppCompatActivity {
String Barname;
TextView food,price;
private ListView reciepeListView;
private ProgressDialog loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reciepe);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setBackgroundColor(Color.parseColor("#FFBC03"));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
new JSONTask().execute("http://thehostels.in/Foody/reciepe_json.php");
DisplayImageOptions options = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(Reciepe.this)
.defaultDisplayImageOptions(options)
.build();
com.nostra13.universalimageloader.core.ImageLoader.getInstance().init(config);
reciepeListView = (ListView)findViewById(R.id.list_recipe);
Intent intent=getIntent();
if(intent!=null){
Barname=intent.getStringExtra("Type");
Log.e("Type",Barname);
}
if (Barname != null) {
switch (Barname) {
case "Punjabi":
getSupportActionBar().setTitle("Punjabi");
break;
case "Chinese":
getSupportActionBar().setTitle("Chinese");
break;
case "South Indian":
getSupportActionBar().setTitle("South Indian");
break;
case "Gujarati":
getSupportActionBar().setTitle("Gujarati");
break;
case "Chicken":
getSupportActionBar().setTitle("Chicken");
break;
}
}
}
public class JSONTask extends AsyncTask<String, String, List<Listview_reciepe_conveyer>> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(Reciepe.this, "loading,please wait...", null, true, true);
}
#Override
protected List<Listview_reciepe_conveyer> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("list");
List<Listview_reciepe_conveyer> fixture_conveyerList = new ArrayList<Listview_reciepe_conveyer>();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
Listview_reciepe_conveyer fixtureList = new Listview_reciepe_conveyer();
fixtureList.setImage(finalObject.getString("image"));
fixtureList.setFood(finalObject.getString("food"));
fixtureList.setPrice(finalObject.getString("price"));
fixture_conveyerList.add(fixtureList);
}
return fixture_conveyerList;
}catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<Listview_reciepe_conveyer> result) {
super.onPostExecute(result);
if (result !=null) {
loading.dismiss();
ListAdapter adapter = new ListAdapter(Reciepe.this, R.layout.custom_recipe_list, result);
reciepeListView.setAdapter(adapter);
}
else
{
Toast.makeText(Reciepe.this, "No Internet Connection!", Toast.LENGTH_LONG).show();
loading.dismiss();
}
}
}
public class ListAdapter extends ArrayAdapter {
private List<Listview_reciepe_conveyer> reciepe_conveyerList;
private int resource;
private LayoutInflater inflater;
public ListAdapter(Context context, int resource, List<Listview_reciepe_conveyer> objects) {
super(context, resource, objects);
reciepe_conveyerList = objects;
this.resource = resource;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(resource, null);
}
ImageView food_photo;
final TextView food,price;
food_photo = (ImageView)convertView.findViewById(R.id.food_photo);
food = (TextView)convertView.findViewById(R.id.food_name);
price = (TextView)convertView.findViewById(R.id.food_price);
ImageLoader.getInstance().displayImage(reciepe_conveyerList.get(position).getImage(), food_photo);
food.setText(reciepe_conveyerList.get(position).getFood());
String newprice= ("Rs."+reciepe_conveyerList.get(position).getPrice());
price.setText(newprice);
reciepeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i=new Intent(Reciepe.this,Description.class);
i.putExtra("Dish",reciepe_conveyerList.get(position).getFood());
i.putExtra("Price",reciepe_conveyerList.get(position).getPrice());
startActivity(i);
}
}
);
return convertView;
}
}
}
this is what my code looks like where i am loading a list from an api,
so i am using AsyncTask to load the listview but i do not know how to make the post request , i have updated the api it os taking the post values but what changes do i need to make on android level.., i have to pass the 'barname' as the post parameter...
On:
protected List<Listview_reciepe_conveyer> doInBackground(String... params) {
Try:
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
params.add(new BasicNameValuePair("firstParam", "paremeterValue"));
//your param nr.1.
//This is the value that you want to send.
//It is represented like 'name=value', or in your case 'firstParam=parameterValue'.
//You need to edit this field in respect to what you are doing.
params.add(new BasicNameValuePair("secondParam", "your2parameter"));
//your param nr.2
//This is the value that you want to send.
//It is represented like 'name=value', or in your case 'secondParam=your2parameter'.
//You need to edit this field in respect to what you are doing.
params.add(new BasicNameValuePair("thirdParam", "anotherParameter"));
//your param nr.3
//This is the value that you want to send.
//It is represented like 'name=value', or in your case 'thirdParam=anotherParameter'.
//You need to edit this field in respect to what you are doing.
// Write(add) parameters to your request
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();
conn.connect();
Before your..:
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
...
EDITED
private String getQuery(List<BasicNameValuePair> params) throws UnsupportedEncodingException
{
StringBuilder result = new StringBuilder();
boolean first = true;
for (String pair : params)
{
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
This function turn's the List params, in a String with the format, 'name=value' which is needed to send via request.
For more info see Query String.
Please do NOT copy and paste the solution, you also need to understand what you are doing and replace variables/methods accordingly, for this code to work.
Best