I'm having a hard time figuring out how to implement the new MyAsyncTask().execute("") that I've searched because I have separate classes that extends Asynctask. I wanted to call the class everytime i click the button. Hope you guys can help me figure this out.
Here is my MainActivity
public class MainActivity extends AppCompatActivity {
String url = "http://192.168.254.103/dbtest/categories.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.start);
final ListView lv = (ListView) findViewById(R.id.lv);
final Downloader d = new Downloader(this,url,lv);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.execute();
}
});
}
}
Here is my Downloader.java
public class Downloader extends AsyncTask<Void,Integer, String> {
Context c;
String address;
ListView lv;
ProgressDialog pd;
public Downloader(Context c, String address, ListView lv) {
this.c = c;
this.address = address;
this.lv = lv;
}
//BEFORE JOB STARTS
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("Fetch Data");
pd.setMessage("Please Wait");
pd.show();
}
#Override
protected String doInBackground(Void... params) {
String data = downloadData();
return data;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
pd.dismiss();
if(s != null){
Parser p =new Parser(c,s,lv);
p.execute();
}else
{
Toast.makeText(c,"Unable to download data",Toast.LENGTH_SHORT).show();
}
}
private String downloadData(){
//connect and get a stream
InputStream is = null;
String line = null;
try{
URL url = new URL(address);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
is = new BufferedInputStream(con.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuffer sb = new StringBuffer();
if(br != null){
while((line = br.readLine()) != null)
{
sb.append(line+"\n");
}
}
else
{
return null;
}
return sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}
and my Parser.java
public class Parser extends AsyncTask<Void,Integer,Integer> {
Context c;
ListView lv;
String data;
ArrayList<String> categories = new ArrayList<>();
ProgressDialog pd;
public Parser(Context c, String data, ListView lv) {
this.c = c;
this.data = data;
this.lv = lv;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("Parser");
pd.setMessage("Please Wait");
pd.show();
}
#Override
protected Integer doInBackground(Void... params) {
return this.parse();
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
if(integer == 1)
{
//ADAPTER
ArrayAdapter<String> adapter = new ArrayAdapter<String>(c, android.R.layout.simple_list_item_1, categories);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
}else
{
Toast.makeText(c,"Unable to Parse",Toast.LENGTH_SHORT).show();
}
pd.dismiss();
}
//PARSE RECEIVED DATA
private int parse(){
try
{
//ADD TGAT DATA TO JSON ARRAY FIRST
JSONArray ja = new JSONArray(data);
//CREATE JO OBJECT TO HOLD A SINGLE ITEM
JSONObject jo = null;
categories.clear();
//LOOP THROUGH ARRAY
for(int i =0 ; i<ja.length();i++)
{
jo = ja.getJSONObject(i);
//RETRIEVE NAME
String name=jo.getString("cat_name");
//ADD TO ARRAY LIST
categories.add(name);
}
return 1;
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
}
Related
im trying to parse data from SQL Database into Listview.
My PHP script is working because if i run it in the browser i get the content.
If im trying to get the data from my SQL Databse into the listview my app shows nothing.
Here is my MainActivity:
public class Locations extends AppCompatActivity implements AdapterView.OnItemClickListener {
ArrayList<productforloc> arrayList;
ListView lv;
private String TAG = Locations.class.getSimpleName();
private TextView addressField; //Add a new TextView to your activity_main to display the address
private LocationManager locationManager;
private String provider;
int i = 1;
private ProgressDialog pDialog;
String name;
// URL to get contacts JSON
private static String url = "Mylink";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
Intent i = getIntent();
String cityname = i.getExtras().getString("cityname");
TextView city = (TextView) findViewById(R.id.ort);
city.setText(cityname);
pDialog = new ProgressDialog(Locations.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(true);
pDialog.show();
arrayList = new ArrayList<>();
lv = (ListView) findViewById(R.id.lv);
lv.setOnItemClickListener((AdapterView.OnItemClickListener) this);
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute(url);
}
});
final ImageButton filteropen = (ImageButton) findViewById(R.id.aufklaupen);
filteropen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RelativeLayout filter = (RelativeLayout) findViewById(R.id.filterloc);
filter.setVisibility(View.VISIBLE);
ImageButton filterclose = (ImageButton) findViewById(R.id.zuklappen);
filterclose.setVisibility(View.VISIBLE);
filteropen.setVisibility(View.INVISIBLE);
}
});
final ImageButton filterclose = (ImageButton) findViewById(R.id.zuklappen);
filterclose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RelativeLayout filter = (RelativeLayout) findViewById(R.id.filterloc);
filter.setVisibility(View.INVISIBLE);
ImageButton filteropen = (ImageButton) findViewById(R.id.aufklaupen);
filteropen.setVisibility(View.VISIBLE);
filterclose.setVisibility(View.INVISIBLE);
}
});
}
class ReadJSON extends AsyncTask<String,Integer,String> {
#Override
protected String doInBackground(String... params) {
return readURL(params[0]);
}
#Override
protected void onPostExecute(String content) {
try{
JSONObject jo = new JSONObject(content);
JSONArray ja = jo.getJSONArray("contacts");
for(int i=0;i<ja.length();i++){
JSONObject po = ja.getJSONObject(i);
arrayList.add(new productforloc(
po.getString("imageurl"),
po.getString("name"),
po.getString("street"),
po.getString("postalcode"),
po.getString("musicstyle"),
po.getString("musicsecond"),
po.getString("entry"),
po.getString("opening"),
po.getString("agegroup"),
po.getString("urlbtn"),
po.getString("Fsk"),
po.getString("city"),
po.getString("bg")
));
}
} catch (JSONException e) {
e.printStackTrace();
}
final CustomListAdapterforloc adapter = new CustomListAdapterforloc(getApplicationContext(),R.layout.model,arrayList);
lv.setAdapter(adapter);
if(pDialog.isShowing()){
pDialog.dismiss();
}
}
}
private String readURL(String url){
StringBuilder content = new StringBuilder();
try{
URL uri = new URL(url);
URLConnection urlConnection = uri.openConnection();
BufferedReader bufferedReader= new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while((line = bufferedReader.readLine()) !=null){
content.append(line+"\n");
}
bufferedReader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return content.toString();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
productforloc pForloc = arrayList.get(position);
Intent intent = new Intent();
intent.setClass(this,DetailActivity.class);
intent.putExtra("name",pForloc.getName());
intent.putExtra("imageurl",pForloc.getImage());
intent.putExtra("street",pForloc.getStreet());
intent.putExtra("postalcode",pForloc.getPostalcode());
intent.putExtra("entry",pForloc.getEntry());
intent.putExtra("agegroup",pForloc.getAgegroup());
intent.putExtra("opening",pForloc.getOpening());
intent.putExtra("urlbtn",pForloc.getUrlbtn());
intent.putExtra("Fsk",pForloc.getFsk());
intent.putExtra("city",pForloc.getCity());
intent.putExtra("musicstyle",pForloc.getMusicstyle());
intent.putExtra("musicsecond",pForloc.getMusicsecond());
intent.putExtra("bg",pForloc.getBg());
startActivity(intent);
}
/**
* Async task class to get json by making HTTP call
}
*/
}
and here is my Customlistadapter Activity:
public class CustomListAdapterforloc extends ArrayAdapter<productforloc>{
ArrayList<productforloc> products;
Context context;
int resource;
public CustomListAdapterforloc(Context context, int resource, List<productforloc> products) {
super(context, resource, products);
this.products = (ArrayList<productforloc>) products;
this.context = context;
this.resource = resource;
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView== null){
LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.model,null,true);
}
productforloc product = getItem(position);
ImageView imageView = (ImageView) convertView.findViewById(R.id.imagelist);
Picasso.with(context).load(product.getImage()).into(imageView);
TextView txtName= (TextView) convertView.findViewById(R.id.namelist);
txtName.setText(product.getName());
return convertView;
}
}
i solved it using this code in my MAinActivity:
public class Locations extends AppCompatActivity {
private String TAG = Locations.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = "http://partypeople.bplaced.net/loli.php";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.lv);
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(Locations.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONArray contacts = new JSONArray(jsonStr);
// Getting JSON Array node
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String email = c.getString("email");
String address = c.getString("address");
String gender = c.getString("gender");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("id", id);
contact.put("name", name);
contact.put("email", email);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**3
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
Locations.this, contactList,
R.layout.model, new String[]{"name", "email",
"mobile"}, new int[]{R.id.namelist,
});
lv.setAdapter(adapter);
}
}
and used in my CustomlistadapterActivity:
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
Thanks for your input
Override getCount method into adapter class.
After Clicking an Item in my List view, my Single Item View should appear. Unfortunately every time i click on one of the two items just the same content appears. How can i fix the problem and the right content will be shown?
First i get parse data in my Main Activity:
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
ArrayList<productforloc> arrayList;
ListView lv;
private String TAG = MainActivity.class.getSimpleName();
private TextView addressField; //Add a new TextView to your activity_main to display the address
private LocationManager locationManager;
private String provider;
int i = 1;
private ProgressDialog pDialog;
String name;
String image;
String street;
String postalcode;
String musicstyle;
String musicsecond;
String entry;
String opening;
String agegroup;
String urlbtn;
String Fsk;
String city;
// URL to get contacts JSON
private static String url = "http://partypeople.bplaced.net/maptest.json";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
arrayList = new ArrayList<>();
lv = (ListView) findViewById(R.id.lv);
lv.setOnItemClickListener((AdapterView.OnItemClickListener) this);
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute(url);
}
});
final Button popbutton = (Button) findViewById(R.id.popbutton);
popbutton.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onClick(View v) {
if (i == 1) {
if (popbutton.isPressed()) {
popbutton.setBackground(getResources().getDrawable(R.drawable.secondbg));
arrayList.clear();
url = "http://partypeople.bplaced.net/justpop.json";
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute(url);
}
});
i = i + 1;
}
} else {
if (popbutton.isPressed()) {
popbutton.setBackground(getResources().getDrawable(R.drawable.bg_popbutton));
arrayList.clear();
url = "http://partypeople.bplaced.net/maptest.json";
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute(url);
}
});
i = i - 1;
}
}
}
});
}
class ReadJSON extends AsyncTask<String,Integer,String>{
#Override
protected String doInBackground(String... params) {
return readURL(params[0]);
}
#Override
protected void onPostExecute(String content) {
if (pDialog.isShowing())
pDialog.dismiss();
try{
JSONObject jo = new JSONObject(content);
JSONArray ja = jo.getJSONArray("contacts");
for(int i=0;i<ja.length();i++){
JSONObject po = ja.getJSONObject(i);
arrayList.add(new productforloc(
image= po.getString("imageurl"),
name = po.getString("name"),
street = po.getString("street"),
postalcode = po.getString("postalcode"),
musicstyle = po.getString("musicstyle"),
musicsecond = po.getString("musicsecond"),
entry = po.getString("entry"),
opening = po.getString("opening"),
agegroup = po.getString("agegroup"),
urlbtn = po.getString("urlbtn"),
Fsk = po.getString("Fsk"),
city = po.getString("city")
));
}
} catch (JSONException e) {
e.printStackTrace();
}
CustomListAdapterforloc adapter = new CustomListAdapterforloc(getApplicationContext(),R.layout.model,arrayList);
lv.setAdapter(adapter);
}
}
private String readURL(String url){
StringBuilder content = new StringBuilder();
try{
URL uri = new URL(url);
URLConnection urlConnection = uri.openConnection();
BufferedReader bufferedReader= new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while((line = bufferedReader.readLine()) !=null){
content.append(line+"\n");
}
bufferedReader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return content.toString();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent();
intent.setClass(this,DetailActivity.class);
intent.putExtra("name",name);
intent.putExtra("imageurl",image);
intent.putExtra("street",street);
intent.putExtra("postalcode",postalcode);
intent.putExtra("musicstyle",musicstyle);
intent.putExtra("musicsecond",musicsecond);
intent.putExtra("entry",entry);
intent.putExtra("opening",opening);
intent.putExtra("agegroup",agegroup);
intent.putExtra("urlbtn",urlbtn);
intent.putExtra("Fsk",Fsk);
intent.putExtra("city",city);
startActivity(intent);
Toast.makeText(getApplicationContext(),street,Toast.LENGTH_LONG).show();
}
/**
* Async task class to get json by making HTTP call
}
*/
}
Then as you can see in the bottom the content will be sent to the detailactivity, but i always get the content from the second item in my json even if i click on the first item.
Change your onItemClick method to get the right object from your list.
Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
productforloc pForloc = arrayList.get(positon);
Intent intent = new Intent();
intent.setClass(this,DetailActivity.class);
intent.putExtra("name",pForloc.getName());
intent.putExtra("imageurl",pForloc.getImage());
intent.putExtra("street",pForloc.getStreet());
intent.putExtra("postalcode",pForloc.getPostalcode());
intent.putExtra("urlbtn",pForloc.getUrlbtn());
intent.putExtra("Fsk",pForloc.getFsk());
intent.putExtra("city",pForloc.getCity());
startActivity(intent);
Toast.makeText(getApplicationContext(),street,Toast.LENGTH_LONG).show();
}
I am have sql DB and I am trying to display queried values in a listView. I created a custom adapter for the listView. problem is
I am not able to see any data displayed on my listView.
code of main
public class _songs_playlist extends AppCompatActivity {
ArrayList<songsarray> listofsoongs = new ArrayList<songsarray>();
private static int SPLASH_TIME_OUT=2000;
AlertDialog alertDialog;
private boolean loggedIn = false;
String type;
String result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity__songs_playlist);
new JSONParse().execute();
MyCustomAdapterSongs itemsAdapter = new MyCustomAdapterSongs(this, listofsoongs);
ListView listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(itemsAdapter);
itemsAdapter.notifyDataSetChanged();
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
alertDialog=new AlertDialog.Builder(_songs_playlist.this).create();
alertDialog.setTitle("Upadting Data");
pDialog = new ProgressDialog(_songs_playlist.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
HTTPHandler sh = new HTTPHandler();
String login_URL = "http://2f179dfb.ngrok.io/getsong.php";
try {
//Fetching the boolean value form sharedpreferences
URL url = new URL(login_URL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
result = "";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
Log.e("RESULT", result);
JSONObject jsonObject = new JSONObject(result);
JSONArray result1 = jsonObject.getJSONArray("result");
for (int i = 0; i < result1.length(); i++) {
JSONObject c = result1.getJSONObject(i);
String id = c.getString("songID");
String names = c.getString("songName");
String ss = c.getString("singerName");
listofsoongs.add(new songsarray(ss,id,names));
}
return jsonObject;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
if(true)
{
}
else
{
}
}
}
}
code of custom array adapter
public class MyCustomAdapterSongs extends ArrayAdapter<songsarray> {
Context context;
ArrayList<songsarray> items;
public MyCustomAdapterSongs(Activity context, ArrayList<songsarray> songsarrays) {
super(context, 0, songsarrays);
this.context=context;
this.items=songsarrays;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.itemlist, parent, false);
}
TextView nameTextView = (TextView) listItemView.findViewById(R.id.textView1);
nameTextView.setText(currentAndroidFlavor.getSingername());
Log.e("hhhh", nameTextView.getText().toString());
TextView numberTextView = (TextView) listItemView.findViewById(R.id.textView2);
numberTextView.setText(currentAndroidFlavor.getSongname());
Log.e("jjjj", numberTextView.getText().toString());
CheckBox ch=(CheckBox)listItemView.findViewById(R.id.checkBox1);
ch.setSelected(currentAndroidFlavor.isSelected());
return listItemView;
}
#Override
public int getCount() {
if(items == null)
return 0;
return items.size();
}
#Override
public songsarray getItem(int i) {
return items.get(i);
}
}
Call itemsAdapter.notifyDataSetChanged() within onPostExecute.
Your list is empty until the AsyncTask finishes there.
You'll have to make the adapter a member variable of the Activity class
As in your code I can see you are updating the list in doInBackground but you are not notifying the adapter for the changes.
In onPostExecute method you need to call itemsAdapter.notifyDataSetChanged() and make sure it you are not calling it inside doInBackground as in background thread you can't to UI related work.
Check the EDITS in this code snippet
`
public class _songs_playlist extends AppCompatActivity {
ArrayList<songsarray> listofsoongs = new ArrayList<songsarray>();
private static int SPLASH_TIME_OUT=2000;
AlertDialog alertDialog;
private boolean loggedIn = false;
String type;
String result;
//EDIT 1: Make these member variables
MyCustomAdapterSongs itemsAdapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity__songs_playlist);
//EDIT 2: get references your views before AsyncTask
listView = (ListView) findViewById(R.id.listView1);
new JSONParse().execute();
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
alertDialog=new AlertDialog.Builder(_songs_playlist.this).create();
alertDialog.setTitle("Upadting Data");
pDialog = new ProgressDialog(_songs_playlist.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
HTTPHandler sh = new HTTPHandler();
String login_URL = "http://2f179dfb.ngrok.io/getsong.php";
try {
//Fetching the boolean value form sharedpreferences
URL url = new URL(login_URL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
result = "";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
Log.e("RESULT", result);
JSONObject jsonObject = new JSONObject(result);
JSONArray result1 = jsonObject.getJSONArray("result");
for (int i = 0; i < result1.length(); i++) {
JSONObject c = result1.getJSONObject(i);
String id = c.getString("songID");
String names = c.getString("songName");
String ss = c.getString("singerName");
listofsoongs.add(new songsarray(ss,id,names));
}
return jsonObject;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
//EDIT 3: set your adapter here as this method will be called on the UI Thread
itemsAdapter = new MyCustomAdapterSongs(this, listofsoongs);
listView.setAdapter(itemsAdapter);
}
}
}
}
`
code which one should I change to throw button and instantly displays my listview without having to click a button
public class MainActivity extends AppCompatActivity {
Button btnLoadFeed; <<<<<------------- Which should I remove associated with this code?
TextView textViewFeedUrl;
ListView listViewFeed;
List<FeedItem> listFeedItems;
ListAdapter adapterFeed;
String myFeed = "http://temfilm.blogspot.co.id/feeds/posts/default?alt=json";
//String myFeed = "http://arduino-er.blogspot.com/feeds/posts/default?alt=json";
//String myFeed = "http://helloraspberrypi.blogspot.com/feeds/posts/default?alt=json";
//String myFeed = "http://photo-er.blogspot.com/feeds/posts/default?alt=json";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnLoadFeed = (Button)findViewById(R.id.loadfeed);
textViewFeedUrl = (TextView)findViewById(R.id.feedurl);
setContentView(R.layout.layout_feed);
listViewFeed = (ListView)findViewById(R.id.listviewfeed);
listFeedItems = new ArrayList<>();
adapterFeed = new ArrayAdapter<FeedItem>(
this, android.R.layout.simple_list_item_1, listFeedItems);
listViewFeed.setAdapter(adapterFeed);
btnLoadFeed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textViewFeedUrl.setText(myFeed);
new JsonTask(listFeedItems, listViewFeed).execute(myFeed);
}
});
}
/*
JsonTask:
AsyncTask to download and parse JSON Feed of blogspot in background
*/
private class JsonTask extends AsyncTask<String, FeedItem, String> {
List<FeedItem> jsonTaskList;
ListView jsonTaskListView;
public JsonTask(List<FeedItem> targetList, ListView targetListView) {
super();
jsonTaskList = targetList;
jsonTaskListView = targetListView;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
jsonTaskList.clear();
jsonTaskListView.invalidateViews();
}
#Override
protected String doInBackground(String... params) {
try {
final String queryResult = sendQuery(params[0]);
parseQueryResult(queryResult);
} catch (IOException e) {
e.printStackTrace();
final String eString = e.toString();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this,
eString,
Toast.LENGTH_LONG).show();
}
});
} catch (JSONException e) {
e.printStackTrace();
final String eString = e.toString();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this,
eString,
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onProgressUpdate(FeedItem... values) {
FeedItem newItem = values[0];
jsonTaskList.add(newItem);
jsonTaskListView.invalidateViews();
}
private String sendQuery(String query) throws IOException {
String queryReturn = "";
URL queryURL = new URL(query);
HttpURLConnection httpURLConnection = (HttpURLConnection)queryURL.openConnection();
if(httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK){
InputStreamReader inputStreamReader =
new InputStreamReader(httpURLConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader, 8192);
String line = null;
while((line = bufferedReader.readLine()) != null){
queryReturn += line;
}
bufferedReader.close();
}
return queryReturn;
}
private void parseQueryResult(String json) throws JSONException {
JSONObject jsonObject = new JSONObject(json);
final JSONObject jsonObject_feed = jsonObject.getJSONObject("feed");
final JSONArray jsonArray_entry = jsonObject_feed.getJSONArray("entry");
runOnUiThread(new Runnable() {
#Override
public void run() {
if(jsonArray_entry == null){
Toast.makeText(MainActivity.this,
"jsonArray_entry == null",
Toast.LENGTH_LONG).show();
}else{
Toast.makeText(MainActivity.this,
String.valueOf(jsonArray_entry.length()),
Toast.LENGTH_LONG).show();
for(int i=0; i<jsonArray_entry.length(); i++){
try {
JSONObject thisEntry = (JSONObject) jsonArray_entry.get(i);
JSONObject thisEntryTitle = thisEntry.getJSONObject("title");
String thisEntryTitleString = thisEntryTitle.getString("$t");
JSONArray jsonArray_EntryLink = thisEntry.getJSONArray("link");
//search for the link element with rel="alternate"
//I assume it's one and only one element with rel="alternate",
//and its href hold the link to the page
for(int j=0; j<jsonArray_EntryLink.length(); j++){
JSONObject thisLink = (JSONObject) jsonArray_EntryLink.get(j);
try{
String thisLinkRel = thisLink.getString("rel");
if(thisLinkRel.equals("alternate")){
try{
String thisLinkHref = thisLink.getString("href");
FeedItem thisElement = new FeedItem(
thisEntryTitleString.toString(),
thisLinkHref);
publishProgress(thisElement);
break;
}catch (JSONException e){
//no such mapping exists
}
}
}catch (JSONException e){
//no such mapping exists
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
});
}
}
}
My data comes dynamically in an array of textviews and I am entering some data in edit texts beside that.
All the data comes in the listview.
what I need to do is I need to transfer all the data in the text views as well as edittexts to another screen on a button click.
How will I achieve that?
Here is my code:
public class S1 extends ListActivity implements OnClickListener {
private ProgressDialog pDialog;
ListView lv;
Button b;
String arry1[], category_main;
int i,key = 0;
private static String url = "http://ashapurasoftech.com/train/test.json";
private static final String TAG_a = "menu",TAG_Name = "Name",TAG_Cat = "Category";
JSONArray items = null;
ArrayList<HashMap<String, String>> itemList;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.table1);
lv =getListView();
category_main = "";
new Getitems().execute(category_main);
b =(Button) findViewById(R.id.start);
b.setOnClickListener(this);
itemList = new ArrayList<HashMap<String, String>>();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_Name, name);
startActivity(in);
}
});
}
#Override
public void onClick(View arg0) {
switch(arg0.getId()){
case R.id.start: try {
onbuttonclick();
} catch (JSONException e) {
e.printStackTrace();
}
break;
}
}
private void onbuttonclick() throws JSONException {
Set<String> arry = new HashSet<String>();
for(int k=0;k<items.length();k++)
{
JSONObject c = items.getJSONObject(k);
String category = c.getString(TAG_Cat);
arry.add(category);
}
arry1 = arry.toArray(new String[arry.size()]);
TableRow[] tr = new TableRow[arry1.length];
TextView[] tx = new TextView[arry1.length];
TableLayout tl = (TableLayout) findViewById(R.id.tablelayout1);
for (i = 0; i < arry1.length; i++) {
final String cat = arry1[i].toString();
tx[i] = new TextView(S1.this);
tx[i].setLayoutParams(new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
tx[i].setText(cat);
tr[i] = new TableRow(S1.this);
tr[i].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
tr[i].addView(tx[i],new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
tl.addView(tr[i],new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
tx[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
category_main = cat;
if (key==0)
{
key=1;
lv.setVisibility(View.VISIBLE);
}
else if(key==1)
{
key=0;
lv.setVisibility(View.GONE);
}
new Getitems().execute(category_main);
}
});
}
b.setVisibility(View.GONE);
}
private class Getitems extends AsyncTask<Void, Void, Void> {
String cat12 = "";
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(S1.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(true);
pDialog.show();
}
public void execute(String categorymain) {
cat12 = categorymain;
execute();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
items = jsonObj.getJSONArray(TAG_a);
for (i = 0; i < items.length(); i++) {
final JSONObject c = items.getJSONObject(i); String cate12 = c.getString(TAG_Cat);
String name = c.getString(TAG_Name);
final HashMap<String, String> item = new HashMap<String, String>();
if(cat12.equalsIgnoreCase(cate12))
{
item.put(TAG_Name,name);
itemList.add(item);
}
}
}
catch (JSONException e) {
e.printStackTrace();
} finally {
}}
else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
ListAdapter adapter = new SimpleAdapter(
S1.this, itemList,
R.layout.textview, new String[] {TAG_Name},new int[] { R.id.name});
setListAdapter(adapter);
}
}
}