This question already has answers here:
Why The constructor ArrayAdapter<String>(new View.OnKeyListener(){}, int, String[]) is undefined
(4 answers)
Closed 8 years ago.
this is what i see in the error line
-Multiple markers at this line
- ArrayAdapter is a raw type.
-References to generic type ArrayAdapter should be parameterized
- The constructor ArrayAdapter(RetrieveActivity.MyAsyncTask, int, ArrayList) is
undefined
may i know what is wrong with my code. I wanna display arraylist into the listview. but i can't make it due to the error. tq
package com.example.m2mai;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class RetrieveActivity extends Activity {
ArrayAdapter mArrayAdapter;
ArrayList mNameList = new ArrayList();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_retrieve);
}
public void getStream(View v)
{
new MyAsyncTask().execute();
}
private class MyAsyncTask extends AsyncTask<String, Void, String>
{
public ArrayList<String> atList=new ArrayList<String>();
public ArrayList<String> dataList=new ArrayList<String>();
protected String doInBackground(String... params)
{
return getData();
}
public long getDateTo()
{
EditText toText = (EditText)findViewById(R.id.dateTo);
String To = toText.getText().toString();
DateFormat dateFormatTo = new SimpleDateFormat("dd/MM/yyyy");
Date dateTo = null;
try {
dateTo = dateFormatTo.parse(To);
} catch (java.text.ParseException e) {
e.printStackTrace();
}
long timeTo = dateTo.getTime();
new Timestamp(timeTo);
return timeTo/1000;
}
protected String getData()
{
String toTS = ""+getDateTo();
String decodedString="";
String returnMsg="";
String request = "http://api.carriots.com/devices/defaultDevice#eric3231559.eric3231559/streams/?order=-1&max=5&at_to="+toTS;
URL url;
HttpURLConnection connection = null;
try {
url = new URL(request);
connection = (HttpURLConnection) url.openConnection();
//establish the parameters for the http post request
connection.addRequestProperty("carriots.apikey", "====================");
connection.addRequestProperty("Content-Type", "application/json");
connection.setRequestMethod("GET");
//create a buffered reader to interpret the incoming message from the carriots system
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((decodedString = in.readLine()) != null)
{
returnMsg+=decodedString;
}
in.close();
connection.disconnect();
JSONObject nodeRoot = new JSONObject(returnMsg);
JSONArray res = nodeRoot.getJSONArray("result");
for (int i = 0; i < res.length(); i++)
{
JSONObject childJSON = res.getJSONObject(i);
if (childJSON.get("data")!=null)
{
String value = childJSON.getString("data");
dataList.add(value);
JSONObject node=new JSONObject(value);
atList.add(node.get("temperature").toString());
}
}
}
catch (Exception e)
{
e.printStackTrace();
returnMsg=""+e;
}
//Log.d("returnMsg",returnMsg.toString());
return returnMsg;
}
protected void onPostExecute(String result)
{
// int a = atList.size();
// String b = ""+a;
// Log.d("atList",b);
for(int i = 0; i < atList.size(); i++)
{
ListView mainListView = (ListView) findViewById(R.id.listView1);
// Create an ArrayAdapter for the ListView
mArrayAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,mNameList); //<---- error here
// Set the ListView to use the ArrayAdapter
mainListView.setAdapter(mArrayAdapter);
mNameList.add(atList.get(i).toString());
mArrayAdapter.notifyDataSetChanged();
}
Toast.makeText(getApplicationContext(),result, Toast.LENGTH_LONG).show();
EditText myData1=(EditText)findViewById(R.id.editText1);
myData1.setText(atList.get(0));
}
}
}
ArrayAdapter is a raw type.
it is expecting that you provide the type of object the adapter is going to handle. For instance,
ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(...
The constructor ArrayAdapter(RetrieveActivity.MyAsyncTask, int,
ArrayList)
The first argument of the constructor is a Context object and not an instance of your AsyncTask (which this is referring to, in your case)
ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(NameOfYoutActivity.this, ...
In onPostExecute you are creating multiple instance of your Adapter. I do think that is not useful
#Override
protected void onPostExecute(String result) {
ListView mainListView = (ListView) findViewById(R.id.listView1);
mArrayAdapter = new ArrayAdapterString> (NameOfYoutActivity.this, android.R.layout.simple_list_item_1,mNameList);
for(int i = 0; i < atList.size(); i++) {
mArrayAdapter.add(atList.get(i).toString());
}
Toast.makeText(getApplicationContext(),result, Toast.LENGTH_LONG).show();
EditText myData1=(EditText)findViewById(R.id.editText1);
myData1.setText(atList.get(0));
}
Also specify the specify the parameters for the type of array adapter to remove warnings like this
ArrayAdapter<String> mArrayAdapter = new ArrayAdapter<String>(RetrieveActivity.this,android.R.layout.simple_list_item_1,mNameList);
Also change the definition of arraylist to
ArrayList<String> mNameList = new ArrayList<String>();
// "this" is not application context.
mArrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, mNameList);
You can create UI in onCreate() method and use mArrayAdapter.notifyDataSetChanged(); for update.
Related
This question already has answers here:
What arguments are passed into AsyncTask<arg1, arg2, arg3>?
(5 answers)
Closed 3 years ago.
I am working on an Android app in which I am making a weather app. The application opens api data from a JSON and displays this information. More specifically it takes the user input of a city or zip code and adds this info to the URL for the API and then executes the URL.
MainActivity.java
package com.shanehampcsci3660.weather;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
//import static com.shanehampcsci3660.weather.GetJsonData.*;
public class MainActivity extends AppCompatActivity
{
public static TextView tempTV, jsonTV;
public EditText cityORZipET;
private Button getWeather;
public String zip, cityOrZip;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tempTV = (TextView) findViewById(R.id.tempTV);
jsonTV = (TextView) findViewById(R.id.jsonFeedTV);
cityORZipET = (EditText) findViewById(R.id.cityORZipET);
getWeather = (Button) findViewById(R.id.getWeatherButton);
//cityOrZip = cityORZipET.getText().toString();
getWeather.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
GetJsonData getJsonData = new GetJsonData();
//getJsonData.execute();
cityOrZip = cityORZipET.getText().toString();
getJsonData.execute("https://api.openweathermap.org/data/2.5/weather?q=" + cityOrZip +"&appid=x");
jsonTV.setText(cityOrZip);
/*if(cityOrZip.equals(""))
{
getJsonData.execute("https://api.openweathermap.org/data/2.5/weather?q=" + cityOrZip +"&appid=x");
}
else
{
zip = "30528";
getJsonData.execute("https://api.openweathermap.org/data/2.5/weather?q=" + zip + "&appid=x");
}*/
}
});
}
}
GetJsonData.java
package com.shanehampcsci3660.weather;
import android.os.AsyncTask;
import android.util.Log;
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.MalformedURLException;
import java.net.URL;
public class GetJsonData extends AsyncTask<Void, Void, Void>
{
public String data= "", line = "", name = "";
double temp, minTemp, maxTemp;
#Override
protected Void doInBackground(Void... voids)
{
try
{
URL url = new URL("https://api.openweathermap.org/data/2.5/weather?q=30528&appid=id");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
while(line != null)
{
line = bufferedReader.readLine();
data = data + line;
}
JSONObject jsonObject = new JSONObject(data);
JSONObject main = jsonObject.getJSONObject("main");
name = jsonObject.getString("name");
temp = main.getDouble("temp");
minTemp = main.getDouble("min_temp");
maxTemp = main.getDouble("max_temp");
/*JSONObject jsonObject = new JSONObject(result);
JSONObject jsonData = new JSONObject(jsonObject.getString("main"));
String weatherInfo = jsonObject.getString("weather");
JSONArray jsonArray = new JSONArray(weatherInfo);
String description, icon, iconURI;
for(int i = 0; i < jsonArray.length(); i++)
{
JSONObject jsonData1 = jsonArray.getJSONObject(i);
description = jsonData1.getString("description");
MainActivityController.description.setText(description);
icon = jsonData1.getString("icon");
iconURI = "http://openweathermap.org/img/w/" + icon + ".png";
Picasso.get().load(iconURI).into(MainActivityController.conditionImageView);
}*/
}
catch(MalformedURLException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
catch (JSONException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid)
{
super.onPostExecute(aVoid);
//MainActivity.jsonTV.setText(data);
MainActivity.tempTV.setText("City:\t" + name + "\tTemp:\t" + temp);
Log.d("Json Feed", name + "Temp: " + temp);
}
public static void execute(String s) {
}
}
My issue is that no matter where I put...
if(cityOrZip.equals(""))
{
getJsonData.execute("https://api.openweathermap.org/data/2.5/weather?q=" + cityOrZip +"&appid=id");
}
else
{
zip = "30528";
getJsonData.execute("https://api.openweathermap.org/data/2.5/weather?q=" + zip + "&appid=id");
}
...It will only show the data of the default Url opened in GetJsonData.java. My question is what am I doing wrong and what should I correct in order to make my app work with the user input like it should.
you are calling an GetJsonData.execute with the url that contains the client data, but it has no code in it. Looking at your current code the zip that the client inputs does not get stored into the worker class.
This is because you always use the same URL in GetJsonData class. According to question What arguments are passed into AsyncTask? your class declaration should look like:
public class GetJsonData extends AsyncTask<String, Void, YourPojo> {
#Override
protected YourPojo doInBackground(String... urls)
{
try
{
URL url = new URL(urls[0]);
...
} catch (Exception e) {
handle(e);
}
}
}
where YourPojo is a class you need to create to store all properties you need to read from JSON payload:
class YourPojo {
private String data;
private String line;
private String name;
private double temp;
private double minTemp
private double maxTemp;
// getters, setters
}
Been trying to write an app in android studio. Part of the app has to parse a document in JSON and display two TextViews of data for each instance. One being Signal and the other being Noise. I am trying to make a custom list view in case I want to add more detail to each instance. I also would like to make it all contained in a ScrollView. I initially had no problems parsing the document but now that I am trying to implement the ListAdapter I am running into issues.
My code is giving me the error...
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.yesinc.tsi880, PID: 4919
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at com.yesinc.tsi880.TelemetryActivity$JSONTask.onPostExecute(TelemetryActivity.java:136)
at com.yesinc.tsi880.TelemetryActivity$JSONTask.onPostExecute(TelemetryActivity.java:50)
Not sure if the problem is with the document that I am trying to parse or the java code itself. Any help would be much appreciated. Code is below.
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.yesinc.tsi880.models.SondeModel;
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.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import android.widget.ArrayAdapter;
public class TelemetryActivity extends AppCompatActivity {
private TextView tvData;
private ListView lvSondes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_telemetry);
ListView lvSondes = findViewById(R.id.lvSondes);
//new JSONTask().execute("http://172.16.5.70/plots/sigstr2.txt");
}
public class JSONTask extends AsyncTask<String, String, List<SondeModel> >{
#Override
protected List<SondeModel> 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);
JSONObject parentArray0 = parentObject.getJSONObject("0");
JSONObject parentArray1 = parentObject.getJSONObject("1");
List<SondeModel> sondeModelList = new ArrayList<>();
//StringBuffer finalBufferedData = new StringBuffer();
for(int i=0; i<8; i++){
String sonde = String.valueOf(i);
JSONObject finalObject = parentArray0.getJSONObject(sonde);
SondeModel sondeModel = new SondeModel();
sondeModel.setNoisedbm(finalObject.getString("noisedbm"));
sondeModel.setSigdbm(finalObject.getString("sigdbm"));
//String noiseDBM = finalObject.getString("noisedbm");
//String sigDBM = finalObject.getString("sigdbm");
sondeModelList.add(sondeModel);
}
for(int i=0; i<8; i++){
String sonde = String.valueOf(i);
JSONObject finalObject = parentArray1.getJSONObject(sonde);
SondeModel sondeModel = new SondeModel();
sondeModel.setNoisedbm(finalObject.getString("noisedbm"));
sondeModel.setSigdbm(finalObject.getString("sigdbm"));
//String noiseDBM = finalObject.getString("noisedbm");
//String sigDBM = finalObject.getString("sigdbm");
sondeModelList.add(sondeModel);
}
return sondeModelList;
} 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<SondeModel> result) {
super.onPostExecute(result);
SondeAdapter adapter = new SondeAdapter(getApplicationContext(), R.layout.row, result);
lvSondes.setAdapter(adapter);
// TODO need to set a data to the List
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.navigation, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.navigation_telemetry) {
new JSONTask().execute("http://172.16.5.70/plots/sigstr2.txt");
return true;
}
return super.onOptionsItemSelected(item);
}
public class SondeAdapter extends ArrayAdapter{
public List<SondeModel> sondeModelList;
private int resource;
private LayoutInflater inflater;
public SondeAdapter(Context context, int resource, List<SondeModel> objects) {
super(context, resource, objects);
sondeModelList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
convertView = inflater.inflate(resource, null);
}
TextView sig;
TextView noise;
sig = (TextView)convertView.findViewById(R.id.sig);
noise = (TextView)convertView.findViewById(R.id.noise);
sig.setText(sondeModelList.get(position).getSigdbm());
noise.setText(sondeModelList.get(position).getNoisedbm());
return convertView;
}
}
}
ListView lvSondes = findViewById(R.id.lvSondes);
You are re-declaring the lvSondes inside your onCreate method. The class member list view is never used and is never initialized. Instead a local lvSondes is initialized. This variable will not be in scope and won't be visible to the AsyncTask. The async task will use the member variable and that will be null.
Solution: remove the ListView from the stated line and just initialize the member variable
I am an android newbie who is trying to populate spinner using JSON but I keep getting Null Pointer Exception -
java.lang.NullPointerException: Attempt to invoke interface method
java.lang.Object[] java.util.Collection.toArray()' on a null object
reference
I understand that this is a frequently asked question, and have looked through the other answers and solutions. I have tried initializing the List but still, am unable to fix the error.I think I am having trouble understanding where the initialization is exactly needed.
My Complete log:
07-19 09:34:54.356 11199-11337/com.genx.meghna.makdver4 D/Result is: [{"car_number":"DL 2345"},{"car_number":"DL 53546"},{"car_number":"1472"},{"car_number":"m7894"},{"car_number":"nxjvjsv"}]
07-19 09:34:54.356 11199-11337/com.genx.meghna.makdver4 D/res =: [{"car_number":"DL 2345"},{"car_number":"DL 53546"},{"car_number":"1472"},{"car_number":"m7894"},{"car_number":"nxjvjsv"}]
07-19 09:34:54.357 11199-11337/com.genx.meghna.makdver4 E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #3
Process: com.genx.meghna.makdver4, PID: 11199
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object[] java.util.Collection.toArray()' on a null object reference
at java.util.ArrayList.addAll(ArrayList.java:188)
at com.genx.meghna.makdver4.Fragments.SendCarFragment$GetData.doInBackground(SendCarFragment.java:173)
at com.genx.meghna.makdver4.Fragments.SendCarFragment$GetData.doInBackground(SendCarFragment.java:117)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
My code :
package com.genx.meghna.makdver4.Fragments;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.genx.meghna.makdver4.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import static com.genx.meghna.makdver4.Fragments.LoginFragment.un;
public class SendCarFragment extends Fragment {
TextView tv1, tv2, tv3;
Spinner sp;
RadioGroup rg;
RadioButton rb1, rb2;
Button btn;
FragmentManager fm;
ArrayList<String> carList;
ArrayAdapter<String> adapter;
String res;
SharedPreferences spp;
public SendCarFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_send_car, container, false);
btn = rootView.findViewById(R.id.nextPage1);
rg = rootView.findViewById(R.id.radioGroup1);
rb1 = rootView.findViewById(R.id.rb1);
rb2 = rootView.findViewById(R.id.rb2);
sp = rootView.findViewById(R.id.spinnerSelectCar);
spp=getContext().getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (rg.getCheckedRadioButtonId() == -1) {
Toast.makeText(getContext(), "Select One Option", Toast.LENGTH_SHORT).show();
} else {
if (rb1.isChecked()) {
fm = getFragmentManager();
fm.beginTransaction().replace(R.id.container, new ServiceCenterListFragment(), "Service center").commit();
} else {
fm = getFragmentManager();
fm.beginTransaction().replace(R.id.container, new SelectionFragment(), "Select Address").commit();
}
}
}
});
return rootView;
}
public void onStart(){
super.onStart();
String username1 = spp.getString(un, "userKey");
GetData get = new GetData();
get.execute(username1);
}
class GetData extends AsyncTask<String, Void, String> {
List<String> list;
protected void onPreExecute(){
super.onPreExecute();
list=new ArrayList<>();
}
#Override
protected String doInBackground(String... params) {
{
try {
String username1 = params[0];
String link = "http://10.0.3.2//Traccar/getCars.php";
String myurl = "username=" + username1;
URL url = new URL(link);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.getOutputStream().write(myurl.getBytes());
int response = connection.getResponseCode();
Log.d("Response code", "" + response);
if (response == HttpURLConnection.HTTP_OK) {
String line;
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader br = new BufferedReader(isr);
StringBuilder buffer = new StringBuilder();
while ((line = br.readLine()) != null) {
buffer.append(line);
//res+=line;
}
Log.d("Result is", buffer.toString());
res = buffer.toString();
Log.d("res = ", res);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
try{
JSONArray jrr = new JSONArray(res);
for (int i=0; i<jrr.length(); i++) {
JSONObject obj = jrr.getJSONObject(i);
String name = obj.getString("car_number");
list.add(name);
}
} catch (JSONException e1) {
e1.printStackTrace();
}
return res;
}
protected void onPostExecute(String res) {
list.addAll(carList);
adapter = new ArrayAdapter<>(getContext(),android.R.layout.simple_list_item_1, carList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(adapter);
}
}
}
One Alternative method I tried was placing my JSON parse code in the onPostExecute() function but I kept having trouble trying to pass my array from doInBackground() to onPostExecute() which led to my onPostExecute() never being used.
Any help would be much appreciated. Thank you!
You have a carList and a list. You don't initialize or add items to carList but try to pass it to list.addAll(carList); which naturally cannot work.
Since the data is already in list you should be able to do this
class GetData extends AsyncTask<String, Void, List<String>> {
List<String> list;
protected void onPreExecute(){
super.onPreExecute();
list=new ArrayList<>();
}
#Override
protected String doInBackground(String... params) {
{
try {
String username1 = params[0];
String link = "http://10.0.3.2//Traccar/getCars.php";
String myurl = "username=" + username1;
URL url = new URL(link);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.getOutputStream().write(myurl.getBytes());
int response = connection.getResponseCode();
Log.d("Response code", "" + response);
if (response == HttpURLConnection.HTTP_OK) {
String line;
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader br = new BufferedReader(isr);
StringBuilder buffer = new StringBuilder();
while ((line = br.readLine()) != null) {
buffer.append(line);
//res+=line;
}
Log.d("Result is", buffer.toString());
res = buffer.toString();
Log.d("res = ", res);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
try{
JSONArray jrr = new JSONArray(res);
for (int i=0; i<jrr.length(); i++) {
JSONObject obj = jrr.getJSONObject(i);
String name = obj.getString("car_number");
list.add(name);
}
} catch (JSONException e1) {
e1.printStackTrace();
}
return list;
}
protected void onPostExecute(List<String> res) {
adapter = new ArrayAdapter<>(getContext(),android.R.layout.simple_list_item_1, res);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(adapter);
}
}
Note that I changed AsyncTask to AsyncTask<String, Void, List<String>> and carList is not needed.
i need help.
just want to know how to pass value to my php using JSON?
in my CategoryFragment code i set value to my cid
cid = catid;
now i want to pass this value to my php using JSON in this code
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://joehamirbalabadan.com/android/android/products.php");
this is my CategoryFragment.java
package com.example.administrator.mosbeau;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.GridView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Created by Administrator on 9/18/2015.
*/
public class CategoryFragment extends Fragment {
public static CategoryFragment newInstance(String id,String name) {
CategoryFragment fragment = new CategoryFragment();
Bundle bundle = new Bundle();
bundle.putString("id", id);
bundle.putString("name", name);
fragment.setArguments(bundle);
return fragment;
}
public CategoryFragment () {
}
EditText tpid, tpname;
String cid;
String cname;
String myJSON;
JSONArray jsonarray;
GridView productgridview;
GridViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
public static String products_id = "products_id";
public static String products_name = "products_name";
public static String products_price = "products_price";
public static String products_image = "products_image";
Boolean InternetAvailable = false;
Seocnd detectconnection;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.categorylayout, container, false);
getActivity().invalidateOptionsMenu();
tpid = (EditText) rootView.findViewById(R.id.tpid);
tpname = (EditText) rootView.findViewById(R.id.tpname);
if(getArguments() != null) {
String catid = getArguments().getString("id");
String catname = getArguments().getString("name");
tpid.setText(catid);
tpname.setText(catname);
cid = catid;
cname = catname;
}
productgridview = (GridView) rootView.findViewById(R.id.productgridview);
//new DownloadJSON().execute();
detectconnection = new Seocnd(getActivity());
InternetAvailable = detectconnection.InternetConnecting();
if (InternetAvailable) {
getProduct();
} else {
NointernetFragment fragment = new NointernetFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
return rootView;
}
public void getProduct(){
class DownloadJSON extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(getActivity());
// Set progressdialog title
mProgressDialog.setTitle(cname);
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://joehamirbalabadan.com/android/android/products.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
try {
// Locate the array name in JSON
JSONObject jsonObj = new JSONObject(myJSON);
jsonarray = jsonObj.getJSONArray("products");
arraylist = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject p = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("products_id", p.getString("products_id"));
map.put("products_name", p.getString("products_name"));
map.put("products_price", p.getString("products_price"));
map.put("products_image", p.getString("products_image"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
adapter = new GridViewAdapter(getActivity(), arraylist);
// Set the adapter to the GridView
productgridview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
DownloadJSON g = new DownloadJSON();
g.execute();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(2);
}
}
after i pass the value i want to use it in this part of my php code
$cid = "CID value here from java";
here is the complete php code..
products.php
<?php
include('dbconnection.php');
$cid = "CID value here from java";
$statement = mysqli_query($con, "SELECT p.products_id, pd.products_name, p.products_price, p.products_image FROM products p INNER JOIN products_description pd ON p.products_id=pd.products_id WHERE p.products_status='1' ORDER BY p.products_sort_order ASC");
$products = array();
while($row = mysqli_fetch_array($statement)){
array_push($products,
array(
'products_id'=>$row[0],
'products_name'=>$row[1],
'products_price'=>$row[2],
'products_image'=>"http://joehamirbalabadan.com/android/images/".$row[3]
));
}
echo json_encode(array("products"=>$products));
mysqli_close($con);
?>
help me to construct my code.. thanks..
use following code for add parameters into http post request.I hope it will help you..!
//Post Data
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("cid", "testid"));
nameValuePair.add(new BasicNameValuePair("test", "testvalue"));
//Encoding POST data
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e) {
// log exception
e.printStackTrace();
}
// finally make POST request.
The list is working fine but the problem is i can't download the file from the web server file system. When i tried clicking one of the list item, the dialog will show up but after a few seconds the app will crash. I am using GenyMotion emulator
The filename is correct and also the url, i guess it's in the saving part
Memo.java
package com.example.androidtablayout;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class Memo extends ListActivity {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ArrayList<HashMap<String, String>> arraylist;
ProgressDialog mProgressDialog, dialog;
JSONParser jsonParser = new JSONParser();
String email;
SessionManager session;
String[] services;
private String url = "http://10.0.3.2/sunshine-ems/memo.php";
// single product url
// ALL JSON node names
private static final String MEMO_ID = "memo_id";
private static final String MEMO_SENDER = "sender";
private static final String MEMO_FILENAME = "file_name";
Button btnLogout;
String username;
String download_path = "";
String dest_file_path = "";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.announc);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
session = new SessionManager(getApplicationContext());
username = session.getUsername();
btnLogout = (Button) findViewById(R.id.btnLogout);
btnLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// Launching All products Activity
session.logoutUser();
Intent i = new Intent(getApplicationContext(), Login.class);
startActivity(i);
}
});
new DownloadJSON().execute();
ListView lv = getListView();
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
String memo_filename = ((TextView) view.findViewById(R.id.txt_service)).getText().toString();
download_path = "http://www.sunshine-ems.balay-indang.com/attachments/memo/"+memo_filename+".docx";
String sd_path = Environment.getExternalStorageDirectory().getPath();
dest_file_path = sd_path+"/"+memo_filename+".docx";
dialog = ProgressDialog.show(Memo.this, "", "Downloading file...", true);
new Thread(new Runnable() {
public void run() {
//Log.d("Download Path", dest_file_path+" "+download_path);
downloadFile(download_path, dest_file_path);
}
}).start();
}
});
}
//download
public void downloadFile(String download_path, String dest_file_path) {
try {
File dest_file = new File(dest_file_path);
URL u = new URL(download_path);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(dest_file));
fos.write(buffer);
fos.flush();
fos.close();
hideProgressIndicator();
} catch(FileNotFoundException e) {
hideProgressIndicator();
return;
} catch (IOException e) {
hideProgressIndicator();
return;
}
}
void hideProgressIndicator(){
runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
}
});
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(Memo.this);
mProgressDialog.setTitle("Loading Services");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
username = session.getUsername();
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
params1.add(new BasicNameValuePair("username", username));
JSONObject json = jsonParser.makeHttpRequest(url, "POST", params1);
// Check your log cat for JSON reponse
Log.d("Check JSON ", json.toString());
// Create the array
arraylist = new ArrayList<HashMap<String, String>>();
try {
int success = json.getInt("success");
if (success == 1) {
// Locate the array name
jsonarray = json.getJSONArray("memos");
for (int i = 0; i < jsonarray.length(); i++) {
json = jsonarray.getJSONObject(i);
String m_id = json.optString(MEMO_ID);
String m_subject = json.getString(MEMO_FILENAME);
String m_sender = json.getString(MEMO_SENDER);
// Retrive JSON Objects
HashMap<String, String> map = new HashMap<String, String>();
map.put(MEMO_ID, m_id);
map.put(MEMO_FILENAME, m_subject);
map.put(MEMO_SENDER, m_sender);
// Set the JSON Objects into the array
arraylist.add(map);
}
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String file_url) {
mProgressDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
Memo.this,
arraylist,
R.layout.listview_services,
new String[] { MEMO_ID, MEMO_FILENAME, MEMO_SENDER },
new int[] { R.id.transac_id, R.id.txt_service,
R.id.txt_date });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
I think the downloading was fine, maybe the problem is in the saving/writing part. Maybe the destination path or something close to that
And also where can i see the downloaded file after the download?
I'm using GenyMotion emulator
I'm sorry for the noob questions
Thank you so much
The problem seems to be this line (because it is the only array):
byte[] buffer = new byte[contentLength];
Looking at the declaration of contentLenght it seems conn.getContentLength() is returning a negative number.
Returns the content length in bytes specified by the response header field
content-length or -1 if this field is not set or cannot be represented as an int.
I copied your code and checked with a debugger: contentLenght is always -1.
I just rewrote your downloadFile function to use HttpURLConnection instead of URLConnection. Additionally, it uses a small buffer multiple times instead of creating one large buffer.
//download
public void downloadFile(String download_path, String dest_file_path) {
try {
URL u = new URL(download_path);
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
InputStream stream = conn.getInputStream();
File f = new File(dest_file_path);
FileOutputStream fos = new FileOutputStream(f);
int bytesRead = 0;
byte[] buffer = new byte[4096];
while ((bytesRead = stream.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
fos.close();
stream.close();
hideProgressIndicator();
} catch(FileNotFoundException e) {
hideProgressIndicator();
return;
} catch (IOException e) {
hideProgressIndicator();
return;
}
}
You can view the file afterwards by using ADB. Android device monitor contains a file explorer and is located at "path-to\AndroidSDK\tools\monitor.bat" (using Windows)