How to set values in spinner dynamically - android

I am working on an android application. I am able to display values from the database into the listview but i want to display them into the spinner instead of listview. Here is the code which i have written for listview
package com.example.festipedia_logo;
//import com.actionbarsherlock.app.SherlockFragment;
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 com.actionbarsherlock.app.SherlockFragmentActivity;
import com.example.festipedia_logo.details2.LoadAllProducts;
import android.app.Activity;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class mainpageact extends SherlockFragmentActivity {
Button button1;
Button button4;
ArrayAdapter<String> adapter1;
// String[] city;
String loc;
Spinner spinner;
String location;
ArrayAdapter<String> adapter;
String[] city;
// Progress Dialog
private ProgressDialog pDialog;
String az;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
EditText b;
// ArrayList<HashMap<String, String>> productsList;
ArrayList<String> productsList;
// url to get all products list
private static String url_all_products = "http://192.168.0.104:8080/festipedia/sports.php";
Button a;
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_NAME = "eventname";
// products JSONArray
JSONArray products = null;
ListView l;
// Spinner spinner;
//String loc;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
getActionBar().setDisplayShowTitleEnabled(false);
getActionBar().setDisplayUseLogoEnabled(false);
getActionBar().setDisplayShowCustomEnabled(true);
getActionBar().setDisplayShowHomeEnabled(false);
//getSupportActionBar().setIcon(R.drawable.fest);
//getSupportActionBar().setLogo(R.drawable.fest);
Drawable d=getResources().getDrawable(R.drawable.a5);
getActionBar().setBackgroundDrawable(d);
setContentView(R.layout.mainmenu);
spinner = (Spinner)this.findViewById(R.id.spinner1);
spinner.setAdapter(adapter);
productsList = new ArrayList<String>();
// productsList = new ArrayList<HashMap<String, String>>();
new LoadAllProducts().execute();
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
location=spinner.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}});
// View rootView = inflater.inflate(R.layout.mainmenu, container, false);
//Intent in = getIntent();
//loc = in.getStringExtra("loc");
Button button1 = (Button) findViewById(R.id.button1);
Button button4 = (Button) findViewById(R.id.button4);
Button button2 = (Button) findViewById(R.id.button2);
Button button5 = (Button) findViewById(R.id.button5);
Button button3 = (Button) findViewById(R.id.button3);
//TextView t1= (TextView) findViewById(R.id.getlocation);
//t1.setText(loc);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
/*final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame,new home1() , "Fest Content");
ft.commit();*/
Intent i = new Intent(getApplicationContext(),
MainActivity.class);
// Closing all previous activities
//i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
//new CreateNewProduct().execute();
}
});
button4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
/* final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame,new testing() , "Fest Content");
ft.commit();*/
Intent i = new Intent(getApplicationContext(),
testing.class);
// Closing all previous activities
//i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
//new CreateNewProduct().execute();
}
});
button5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
/* final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame,new testing() , "Fest Content");
ft.commit();*/
Intent i = new Intent(getApplicationContext(),
search.class);
startActivity(i);
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
/*final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame,new home1() , "Fest Content");
ft.commit();*/
Intent i = new Intent(getApplicationContext(),
MainActivity.class);
// Closing all previous activities
//i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
//new CreateNewProduct().execute();
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
/*final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame,new home1() , "Fest Content");
ft.commit();*/
Intent i = new Intent(getApplicationContext(),
CopyMainActivity.class);
// Closing all previous activities
//i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.putExtra("location", location);
// starting new activity and expecting some response back
startActivityForResult(i, 100);
//startActivity(i);
//new CreateNewProduct().execute();
}
});
}
class LoadAllProducts extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(mainpageact.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("location", az));
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
// String name = c.getString(TAG_NAME);
// city[i] = name;
String name = c.getString(TAG_NAME);
productsList.add(name);
//l.setFilterText(id);
// creating new HashMap
// HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
// map.put(TAG_NAME, name);
// adding HashList to ArrayList
// productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
// city = new String[] { "Mumbai", "Chennai",
// "Dubai"};
// adapter = new ArrayAdapter<String>(mainpageact.this, R.layout.list_item, productsList);
//ArrayAdapter<CharSequence>
adapter = new ArrayAdapter<String>(mainpageact.this,R.layout.mainmenu, productsList);
spinner.setAdapter(adapter);
adapter.notifyDataSetChanged();
//spinner.setAdapter(adapter);
}
});
}
}
}

It seems, that you are not calling notifyDataSetChanged() after you have loaded the Spinner on onPostExecute(). That will tell your adapter that the data of the spinner needs to be refreshed.
So, basically try this:
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
// city = new String[] { "Mumbai", "Chennai",
// "Dubai"};
adapter = new ArrayAdapter<String>(mainpageact.this, productsList,
R.layout.list_item, new String[] {
TAG_NAME},
new int[] { R.id.name });
adapter.notifyDataSetChanged();
}
});
}
NOTE: When you set the spinner to the adapter on your OnCreate(), the adapter is null at that moment. Try doing it inside the onPostExecute(). Also, try to avoid the use of that Thread inside the AsyncTask. It seems unnecessary, but I might be wrong.

There are three issue in your code.
1) Change the productsList declaration as ArrayList( I don't see any need of having HashMap)
So change this line
ArrayList<HashMap<String, String>> productsList;
to
ArrayList<String> productsList;
and instantiate the productsList as
productsList = new ArrayList<String>();
2) In doInBackground() add the response string item directly to the productsList.
String name = c.getString(TAG_NAME);
productsList.add(name);
3) Now the main issue , change the adapter as
adapter = new ArrayAdapter<String>(this,R.layout.list_item, productsList);
spinner.setAdapter(adapter);

Related

How to get specific list item and pass the two values from one activity to another?

I am developing an Android app and I in my SecondActivity I have parsed some JSON values as a listview and I want to open up ThirdActivity when a particular list item is clicked and send the values "name" and "number" to the ThirdActivity.
I have tried by creating an Intent in the OnPostExecute method. But am unable to figure out how to pass the values on to the next activity.
package com.example.acer.videoapp;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class SecondActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView listView1;
Toolbar toolbar1;
String subjectName;
ArrayList<HashMap<String, String>> lessonList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
//setting title to toolbar
toolbar1 = (Toolbar) findViewById(R.id.toolbar1);
Bundle bundle = getIntent().getExtras();
if(bundle!=null) {
toolbar1.setTitle(bundle.getString("Subject"));
subjectName=toolbar1.getTitle().toString();
}
lessonList = new ArrayList<>();
listView1 = (ListView) findViewById(R.id.list);
new GetLessons().execute();
}
/* Async task class to get json by making HTTP call */
private class GetLessons extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(SecondActivity.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 url = getResources().getString(R.string.lessons_url, subjectName);
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
// Getting JSON Array
JSONArray lessons = new JSONArray(jsonStr);
// looping through All lessons
for (int i = 0; i < lessons.length(); i++) {
JSONObject c = lessons.getJSONObject(i);
String number = c.getString("lessonNo");
String name = c.getString("lessonName");
// tmp hash map for single lesson
HashMap<String, String> lesson = new HashMap<>();
// adding each child node to HashMap key => value
lesson.put("number", number);
lesson.put("name", name);
// adding lesson to lesson list
lessonList.add(lesson);
}
} 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();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
SecondActivity.this, lessonList,R.layout.list_item, new String[]{"number", "name",}, new int[]{R.id.lnumber,R.id.lname});
listView1.setAdapter(adapter);
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
Intent intent = new Intent(SecondActivity.this, ThirdActivity.class);
//intent.putExtra("Lesson", listView1.getItemAtPosition(i).toString());
startActivity(intent);
}
});
}
}
}
Can you try this please
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
Intent intent = new Intent(SecondActivity.this, ThirdActivity.class);
HashMap<String, String> lesson = lessonList.get(i);
intent.putExtra("number", lesson.get("number"));
intent.putExtra("name", lesson.get("name"));
startActivity(intent);
}});
Similar question has been asked before. You have most of it in place, just use Intent.PutStringArrayListExtra and then getIntent.getStringArrayListExtra to pass objects between the activities.
Check this:
Intent.putExtra List

Transfer image data from activity to fragment

I have a image in NetworkImageView of a Activity. How to transfer it in another NetworkImageView or ImageView of a Fragment.
first listview
package com.packageNmae;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.enventpc_03.nav11.adater.CustomListAdapter;
import com.enventpc_03.nav11.app.AppController;
import com.enventpc_03.nav11.model.Movie;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class SearchPeople extends BaseActivity {
// Log tag
private static final String TAG = SearchPeople.class.getSimpleName();
// Movies json url
// Movies json url
private static String url = "myurl";
private static String url1 = "my url";
private static String Title = "title";
private static String Location = "loc";
private static String Description = "des";
private static String bitmap = "thumbnailUrl";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
public static final String BITMAP_ID = "id";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, movieList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// // changing action bar color
// getActionBar().setBackgroundDrawable(
// new ColorDrawable(Color.parseColor("#1b1b1b")));
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("fullname"));
movie.setThumbnailUrl(obj.getString("image"));
movie.setRating(obj.getString("location"));
movie.setGenre(obj.getString("Description"));
movie.setYear(obj.getInt("id"));
// // Genre is json array
// JSONArray genreArry = obj.getJSONArray("genre");
// ArrayList<String> genre = new ArrayList<String>();
// for (int j = 0; j < genreArry.length(); j++) {
// genre.add((String) genreArry.get(j));
// }
// movie.setGenre(genre);
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
// listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
// #Override
// public void onItemClick(AdapterView<?> parent, View view, int position,
// long id) {
// Intent intent = new Intent(MainActivity.this, Details.class);
//
//
// startActivity(intent);
// }
// });
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// your code
// TODO Auto-generated method stub
String name = ((TextView) view.findViewById(R.id.title)).getText().toString();
String location = ((TextView) view.findViewById(R.id.rating)).getText().toString();
String description = ((TextView) view.findViewById(R.id.genre)).getText().toString();
bitmap = ((Movie) movieList.get(position)).getThumbnailUrl();
Intent intent = new Intent(SearchPeople.this, Details.class);
intent.putExtra(Title, name);
intent.putExtra(Location, location);
intent.putExtra(Description, description);
intent.putExtra("images", bitmap);
startActivity(intent);
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
public void onBackPressed() {
Intent myIntent = new Intent(SearchPeople.this, UploadActivity.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);// clear back stack
startActivity(myIntent);
finish();
return;
}
// #Override
// public boolean onCreateOptionsMenu(Menu menu) {
// // Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.main, menu);
// return true;
// }
//
// #Override
// public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//
// Intent intent = new Intent(this, Details.class);
// intent.putExtra(BITMAP_ID,position);
// startActivity(intent);
//
// }
}
Full Image View class
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.enventpc_03.nav11.app.AppController;
import com.enventpc_03.nav11.model.Movie;
import java.util.ArrayList;
import java.util.List;
public class Details extends BaseActivity {
private static String Title = "title";
private static String Location = "loc";
private static String Description = "des";
ImageButton fb,google,twitter;
boolean isImageFitToScreen;
private static String bitmap = "thumbnailUrl";
private List<Movie> movieList = new ArrayList<Movie>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
// getActionBar().hide();
//Passing url
MyFragment f = new MyFragment();
Bundle b = new Bundle();
bitmap = ((Movie) movieList.get(position)).getThumbnailUrl();
b.putString("images", bitmap);
f.setArguments(b);
Intent i = getIntent();
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
String name = i.getStringExtra(Title);
String location1 = i.getStringExtra(Location);
String description1 = i.getStringExtra(Description);
String bitmap = i.getStringExtra("images");
final NetworkImageView thumbNail = (NetworkImageView) findViewById(R.id.thumbnail);
thumbNail.setImageUrl(bitmap, imageLoader);
TextView lblname = (TextView) findViewById(R.id.name_label);
TextView location = (TextView) findViewById(R.id.each_location);
TextView description = (TextView) findViewById(R.id.each_comment);
lblname.setText(name);
location.setText(location1);
description.setText(description1);
fb=(ImageButton)findViewById(R.id.fb);
fb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent browserIntent =
new Intent(Intent.ACTION_VIEW, Uri.parse("Facebook"));
startActivity(browserIntent);
}
});
thumbNail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
MyFragment yourFragment= new MyFragment();
fragmentTransaction.add(R.id.myfragment, yourFragment, "FRAGMENT");
fragmentTransaction.commit();
}
});
}
public void onClickHandler(View v) {
switch (v.getId()) {
case R.id.thumbnail:
startActivity(new Intent(this, UploadActivity.class));
}
}
public void onBackPressed() {
Intent myIntent = new Intent(Details.this, SearchPeople.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);// clear back stack
startActivity(myIntent);
finish();
return;
}
Fragment
public class MyFragment extends Fragment {
private static String bitmap = "thumbnailUrl";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View myFragmentView = inflater.inflate(R.layout.fragment_full, container, false);
Bundle bundle = this.getArguments();
String page = bundle.getString("images", bitmap);
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
final NetworkImageView thumbNail = (NetworkImageView)myFragmentView.findViewById(R.id.thumbnail);
thumbNail.setImageUrl(page, imageLoader);
return myFragmentView;
}
}
**Note:**Listview to fulldetail image getting properply but not getting to my frament from details Activity
pass image url through fragment's setArguments() method and fetch it in fragment using getArguments().
thumbNail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
MyFragment yourFragment= new MyFragment();
Bundle b = new Bundle();
b.putString("url", getIntent.getStringExtra("images"));
yourFragment.setArguments(b);
fragmentTransaction.add(R.id.myfragment, yourFragment, "FRAGMENT");
fragmentTransaction.commit();
}
});

Android: Convert ListActivity into ListFragment?

Hello I am using the tutorial from androidhive for working with MySQL and so on.
I want to use the following activity as a fragment - but I have to transfer the ListActivity into ListFragment - when I just change the extend from ListActivity to ListFragment different error appear
AllProductsActivity.java
package com.example.androidhive;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
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.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class AllProductsActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://api.androidhive.info/android_connect/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditProductActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllProductsActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllProductsActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME},
new int[] { R.id.pid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
What I have to change, so I can use that as a fragment?
Edit:
i tried to change the code a little bit following some tutorials on the web...
now it works better, but there is still some problems with onPostExecute...
the doInBackground gets all parameters from mysql. i can track that with debug, but somehow after doInBackground it get's there is an error..
package com.example.androidhive;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
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.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class AllProductsActivity extends ListFragment {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://10.0.2.2/android_connect/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
// products JSONArray
JSONArray products = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
// Hashmap for ListView
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
return inflater.inflate(R.layout.all_products, container, false);
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
getActivity().runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
getActivity(), productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME},
new int[] { R.id.pid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
You must create fragment in FragmentActivity. All code you need is below
MainActivity.java
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_activity);
int index=0;
MyListFragment f = MyListFragment.newInstance(index);
FragmentTransaction ft = getSupportFragmentManager()
.beginTransaction();
ft.replace(R.id.mylist, f);
ft.commit();
}//end oncreate
}//end activity
Layout fragment_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:baselineAligned="false"
android:layout_height="match_parent"
android:orientation="horizontal" >
<FrameLayout
android:id="#+id/mylist"
android:layout_weight="1"
android:layout_width="0px"
android:layout_height="match_parent" />
</LinearLayout>
MyListFragment.java
public class MyListFragment extends ListFragment {
public static MyListFragment newInstance(int index) {
MyListFragment f = new MyListFragment();
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.layout_mylist, container, false);
//read products from web and list
//productsList = new ArrayList<HashMap<String, String>>();
//new LoadProducts().execute();
return v;
}
//end oncreateview
class LoadProducts extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... args) {
return null;
}
protected void onPostExecute(String file_url) {
}
}
//end LoadProducts
}
layout_mylist.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/details"
android:text="some text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/white"
android:textColor="#drawable/black"
android:textStyle="bold"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>

how to get all editext's value from ListItems in android and pass them to api

I have made an activity in that one ListView is ther,In that ListView each listItem is having an editText named "qty",which can be edited,one textView is there which displays "price",I need is when i edit the edittext and if the entered value is more than some limi the textView value will change,After that i have to pass them as a parameter to an api as below:
http://yehki.epagestore.in/app_api/updateCart.php?customer_id=41&product_id=30&quantity=90&product_id=23&quantity=90
from that i will get subtotal's of eact item and have to set them to each item in the list,can anyone please help me for it?My code is as below..Please help me save my life...thank you
main.java
package com.epe.yehki.ui;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.epe.yehki.adapter.CartAdapter;
import com.epe.yehki.backend.BackendAPIService;
import com.epe.yehki.util.Const;
import com.epe.yehki.util.Pref;
import com.example.yehki.R;
public class CartListActivity extends Activity {
private ProgressDialog pDialog;
Intent in = null;
ListView lv;
JSONObject jsonObj;
ArrayList<HashMap<String, String>> cartList;
Bitmap bitmap;;
private CartAdapter cartContent;
JSONArray carts = null;
ImageView back;
TextView tv_place_order, tv_home;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_cart_list);
lv = (ListView) findViewById(R.id.cart_list);
back = (ImageView) findViewById(R.id.iv_bak);
tv_place_order = (TextView) findViewById(R.id.tv_place_order);
tv_home = (TextView) findViewById(R.id.tv_home);
cartList = new ArrayList<HashMap<String, String>>();
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
// execute the cartList api()...........!!!!
new GetCartList().execute();
// listView ClickEvent
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
lv.removeViewAt(position);
cartContent.notifyDataSetChanged();
}
});
tv_home.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
in = new Intent(CartListActivity.this, HomeActivity.class);
startActivity(in);
}
});
tv_place_order.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
/*
* CART LIST PRODUCT LIST...............!!!!!!!!!
*/
private class GetCartList extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(CartListActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
String cartUrl = Const.API_CART_LIST + "?customer_id=" + Pref.getValue(CartListActivity.this, Const.PREF_CUSTOMER_ID, "");
BackendAPIService sh = new BackendAPIService();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(cartUrl, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
if (jsonObj.has(Const.TAG_PRO_LIST)) {
carts = jsonObj.getJSONArray(Const.TAG_PRO_LIST);
if (carts != null && carts.length() != 0) {
// looping through All Contacts
for (int i = 0; i < carts.length(); i++) {
JSONObject c = carts.getJSONObject(i);
String proId = c.getString(Const.TAG_PRODUCT_ID);
String proName = c.getString(Const.TAG_PRODUCT_NAME);
String wPrice = c.getString(Const.TAG_WHOLESALE_PRICE);
String rPrice = c.getString(Const.TAG_RETAIL_PRICE);
String qty = c.getString(Const.TAG_QUANTITY);
String proimg = Const.API_HOST + "/" + c.getString(Const.TAG_PRODUCT_IMG);
HashMap<String, String> cartProduct = new HashMap<String, String>();
cartProduct.put(Const.TAG_PRODUCT_ID, proId);
cartProduct.put(Const.TAG_PRODUCT_NAME, proName);
cartProduct.put(Const.TAG_PRODUCT_IMG, proimg);
cartProduct.put(Const.TAG_WHOLESALE_PRICE, wPrice);
cartProduct.put(Const.TAG_RETAIL_PRICE, rPrice);
cartProduct.put(Const.TAG_QUANTITY, qty);
cartList.add(cartProduct);
}
}
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("::::::::::::::::::got an error::::::::::::");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
*
* */
cartContent = new CartAdapter(CartListActivity.this, cartList);
lv.setAdapter(cartContent);
}
}
}
In ListAdapter, getItem() should return an item using which you populate the Views
#Override
public HashMap<String, String> getItem(int paramInt) {
return cartArray.get(paramInt);
}
To get all values,
final CartAdapter adapter = (CardAdapter) lv.getAdapter();
for (int i = 0; i < adapter.getCount(); i++) {
final HashMap<String, String> item = adapter.getItem(i);
final String quantity = item.get(Const.TAG_QUANTITY); // value of EditText of one row
}

error with calling class that extends asynctask to run it

I'm using class that extends AsyncTask but I have error at the line that executes the class
I couldn't figure it out
here is the class that includes my main class and the class that extends AsyncTask
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.androidhive.library.JSONParser;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.topics_list);
// Hashmap for ListView
TopicsList = new ArrayList<HashMap<String, String>>();
**// Loading products in Background Thread
new LoadAllTopics().execute();**
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// getting values from selected ListItem
String tid = ((TextView) view.findViewById(R.id.tid)).getText()
.toString();
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllTopics extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Topics_list.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest (url_all_topics, "GET", params);
// Check your log cat for JSON reponse
Log.d("All topics: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
topics = json.getJSONArray(TAG_TOPICS);
// looping through All Products
for (int i = 0; i < topics.length(); i++) {
JSONObject c = topics.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_TOPICSID);
String topict = c.getString(TAG_TOPICTITLE);
String username = c.getString(TAG_TOPICAUTHOR);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_TOPICSID, id);
map.put(TAG_TOPICTITLE, topict);
map.put(TAG_TOPICAUTHOR, username);
// adding HashList to ArrayList
TopicsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
/* Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);*/
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
Topics_list.this, TopicsList,
R.layout.list_item, new String[] { TAG_TOPICSID,TAG_TOPICTITLE,
TAG_TOPICAUTHOR},
new int[] { R.id.tid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
} });}}
the error is at the bold line
really appreciate your help
In Java you need to write the method inside the class. Put the onCreate inside Class.
public class MainActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
.....
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// getting values from selected ListItem
String tid = ((TextView) view.findViewById(R.id.tid)).getText()
.toString();
}
});
.........
}
private class LoadAllTopics extends AsyncTask<String, String, String> {
.....
}
}

Categories

Resources