I'm a beginner .
I tried to implement listview in a fragment which data is parsed from json, I'm running in to error
Error is.
Error:(119, 22) error: no suitable constructor found for ProgressDialog(My_Actor)
constructor ProgressDialog.ProgressDialog(Context,int) is not applicable
(actual and formal argument lists differ in length)
constructor ProgressDialog.ProgressDialog(Context) is not applicable
(actual argument My_Actor cannot be converted to Context by method invocation conversion)
Up to my level I don't find anything error here. Please help me out.
MainActivity.java
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
Fragment newFragment = null;
switch (position){
case 0:
newFragment = new My_Actors();
break;
case 1:
newFragment = new My_Editors();
break;
}
if(newFragment!=null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, newFragment)
.commit();
}
}
My_Actors.java
public class My_Actors extends Fragment{
ArrayList<Actors> actorsList;
ActorAdapter adapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
actorsList = new ArrayList<Actors>();
new JSONAsyncTask().execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
View v = inflater.inflate(R.layout.deal_featured, container,false);
ListView listview = (ListView)v.findViewById(R.id.listView1);
adapter = new ActorAdapter(getActivity().getBaseContext(), R.layout.listview_layout, actorsList);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long id) {
// TODO Auto-generated method stub
Toast.makeText(getActivity().getBaseContext(), actorsList.get(position).getName(), Toast.LENGTH_LONG).show();
}
});
return v;
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(Deal_featured.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("actors");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Actors actor = new Actors();
actor.setName(object.getString("name"));
actor.setDescription(object.getString("description"));
actor.setDob(object.getString("dob"));
actor.setCountry(object.getString("country"));
actor.setHeight(object.getString("height"));
actor.setSpouse(object.getString("spouse"));
actor.setChildren(object.getString("children"));
actor.setImage(object.getString("image"));
actorsList.add(actor);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
adapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getActivity().getBaseContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}
ActorAdapter.java
public class ActorAdapter extends ArrayAdapter<Actors> {
ArrayList<Actors> actorList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
public ActorAdapter(Context context, int resource, ArrayList<Actors> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
actorList = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// convert view = design
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.imageview = (ImageView) v.findViewById(R.id.ivImage);
holder.tvName = (TextView) v.findViewById(R.id.tvName);
holder.tvDescription = (TextView) v.findViewById(R.id.tvDescriptionn);
holder.tvDOB = (TextView) v.findViewById(R.id.tvDateOfBirth);
holder.tvCountry = (TextView) v.findViewById(R.id.tvCountry);
holder.tvHeight = (TextView) v.findViewById(R.id.tvHeight);
holder.tvSpouse = (TextView) v.findViewById(R.id.tvSpouse);
holder.tvChildren = (TextView) v.findViewById(R.id.tvChildren);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.imageview.setImageResource(R.drawable.ic_launcher);
new DownloadImageTask(holder.imageview).execute(actorList.get(position).getImage());
holder.tvName.setText(actorList.get(position).getName());
holder.tvDescription.setText(actorList.get(position).getDescription());
holder.tvDOB.setText("B'day: " + actorList.get(position).getDob());
holder.tvCountry.setText(actorList.get(position).getCountry());
holder.tvHeight.setText("Height: " + actorList.get(position).getHeight());
holder.tvSpouse.setText("Spouse: " + actorList.get(position).getSpouse());
holder.tvChildren.setText("Children: " + actorList.get(position).getChildren());
return v;
}
static class ViewHolder {
public ImageView imageview;
public TextView tvName;
public TextView tvDescription;
public TextView tvDOB;
public TextView tvCountry;
public TextView tvHeight;
public TextView tvSpouse;
public TextView tvChildren;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
Error:(119, 22) error: no suitable constructor found for
ProgressDialog(My_Actor) constructor
ProgressDialog.ProgressDialog(Context,int) is not applicable (actual
and formal argument lists differ in length) constructor
ProgressDialog.ProgressDialog(Context) is not applicable (actual
argument My_Actor cannot be converted to Context by method invocation
conversion)
It is clearly says that you have to pass a context and Deal_featured.this is not a context. So instead of
dialog = new ProgressDialog(Deal_featured.this);
You have to use
dialog = new ProgressDialog(getActivity());
getActivity() return the context of this fragment's parent Activity.
Related
The problem is that the getView() method is skipping to view the other images, in short, getView() only displays the 1st and last row of the ListView.
How to populate all the rows in the ListView?
This is my getView() code in my CustomListAdapter, there is no URL included.
I just directly download the images from the API.
public View getView(int position, View convertView, ViewGroup parent) {
RowItemLoyalty rowItem = getItem(position);
if (inflater == null) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item, null);
holder = new Holder();
holder.title = (TextView) convertView.findViewById(R.id.description);
holder.exp = (TextView) convertView.findViewById(R.id.promotion_expiration);
holder.tokensFor = (TextView) convertView.findViewById(R.id.tokensForRedeemOffer);
holder.promotionImages = (ImageView) convertView.findViewById(R.id.promotion_image);
convertView.setTag(holder);
} else {
holder = (Holder) convertView.getTag();
}
holder.title.setText(rowItem.getDescription());
holder.exp.setText(rowItem.getDateEnd());
holder.tokensFor.setText(rowItem.getTokensFor());
//holder.promotionImages.setImageBitmap(rowItem.getImage1());
try {
image_id.put(ConstantKeys.ID, rowItem.getImageId());
} catch (JSONException e) {
e.printStackTrace();
}
ImageDownloadRequest2 request = new ImageDownloadRequest2();
SharedPreferences sharedPreferences = context.getSharedPreferences("USERPASS", 0);
String email = sharedPreferences.getString("username", null);
String password = sharedPreferences.getString("password", null);
request.getToken(email, password, new ApiRequestListener() {
#Override
public void onSuccess(Object object) {
(new GetImageTask() {
#Override
protected void onPostExecute(Bitmap data) {
super.onPostExecute(data);
if (data != null) {
Bitmap[] holderImage = new Bitmap[] {data};
holder.promotionImages.setImageBitmap(holderImage[0]);
Log.d("BITMAPVALUE", String.valueOf(data));
}else
{
holder.promotionImages.setImageResource(R.drawable.app_icon);
}
}
}).execute();
}
#Override
public void onError(String error) {
Log.e("Get Logo", error);
}
});
Log.d("IMAGESTASHLOYALTY", String.valueOf(rowItem.getImageId()));
return convertView;
}
And this is my AsyncTask
private static class GetImageTask extends AsyncTask<Void, Void, Bitmap>
{
#Override
protected Bitmap doInBackground(Void... params)
{
ImageDownload2 manager = ImageDownload2.getInstance();
Bitmap result = null;
try
{
result = manager.apiCall("File/DownloadFiles", image_id.toString(), "C");
}
catch (Exception e)
{
e.printStackTrace();
}
return result;
}
}
Standard misconcept of recycling the views. You give the AsyncTask the holder as parameter. But holder will be a different holder by the time the asynctask is ready with downloading the image.
You better give int position as parameter to the AsyncTask as then you can place the image at the rigth position.
I have following code in which I am struggling to pass value of unique id from the parsed data from json to the DetailActivity.java . I want to use that value of unique_id from Mainactivity.javain DetailActivity.java as a parameter to the URL .I am a newbie so help me out on this.
I am putting the hole Mainactivity.java and DetailActivty.java
public class MainActivity extends AppCompatActivity {
private TextView text1;
private ListView lisView;
private ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create default options which will be used for every
// displayImage(...) call if no options will be passed to this method
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
.defaultDisplayImageOptions(defaultOptions).build();
ImageLoader.getInstance().init(config); // Do it on Application start
lisView = (ListView) findViewById(R.id.lvnews);
new JSONTask().execute("http://cricapi.com/api/cricket");
Button button = (Button)findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JSONTask().execute("http://cricapi.com/api/cricket");
}
});
}
public class JSONTask extends AsyncTask<String, String, List<NewsModel>> {
#Override
protected List<NewsModel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("data");
List<NewsModel> newsModelList = new ArrayList<>();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
NewsModel newsModel = new NewsModel();
newsModel.setHeadline(finalObject.getString("unique_id"));
newsModel.setAuthor(finalObject.getString("description")); // newsModel.setImage(finalObject.getString("Image"));
newsModel.setDescription(finalObject.getString("title"));
newsModelList.add(newsModel);
}
return newsModelList;
} 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(final List<NewsModel> result) {
super.onPostExecute(result);
if(result != null) {
final NewsAdapter newsAdapter = new NewsAdapter(getApplicationContext(), R.layout.row, result);
lisView.setAdapter(newsAdapter);
lisView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
startActivity(intent);
}
});
}
}
}
public class NewsAdapter extends ArrayAdapter{
public List<NewsModel> newsModelList;
private int resource;
private LayoutInflater inflater;
public NewsAdapter(Context context, int resource, List<NewsModel> objects) {
super(context, resource, objects);
newsModelList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView == null){
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.row, null);
holder.headline = (TextView)convertView.findViewById(R.id.headlineview);
holder.author = (TextView)convertView.findViewById(R.id.authorview);
//holder.image = (ImageView)convertView.findViewById(R.id.imageView);
holder.description = (TextView)convertView.findViewById(R.id.descriptionview);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
//holder.headline.setText(newsModelList.get(position).getHeadline());
holder.author.setText(newsModelList.get(position).getAuthor());
holder.description.setText(newsModelList.get(position).getDescription());
return convertView;
}
private class ViewHolder { // private ImageView image;
private TextView headline;
private TextView author;
private TextView description;
}
}
}
Now to the DetailActivity in which I would like to use unique_id as a parameter to URL
public class DetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
// here I want to access that unique_id and pass it as id to url
//Example http://cricapi.com/api/cricketScore?unique_id=946765
}
}
Thanks in Advance
You can use either bundle (or) directly you can send it through the intent itself. Below is the code for Main Activty class
lisView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
//Passing the values to another activty using a unique key..
intent.putExtra("unique_id", newsModelList.get(position).getHeadline());
startActivity(intent);
}
});
Now in details activity get the values with the help of the same unique key.
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
String text = bundle.getString("unique_id");
}
Hope this is helpful.
In the MainActivity, you can add values in the intent like below
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
intent.putString("unique_id", value); startActivity(intent);
In the DetailActivity you can fetch the same value in the onCreate method like this
getIntent().getString("unique_id");
I tried uploading an image using JSON. I create a link to image in JSON. Many times I tried to fix my problem, but with no success.
Is there a mistake in my use of DownloadImageTask in My adapter Adapter ?
MainActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.list);
newsList = new ArrayList<News>();
//this is i take json image
new NewsAsynkTask().execute();
}
public class NewsAsynkTask extends AsyncTask<String , Void, String> {
protected String doInBackground(String... params) {
//code
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
//this i run adapter
NewsAdapter adapter = new NewsAdapter(getApplicationContext(), R.layout.list_row, newsList);
list.setAdapter(adapter);
}
}
My adapter Adapter
public class NewsAdapter extends ArrayAdapter<News> {
ArrayList<News> ArrayListNews;
int Resourse;
Context context;
LayoutInflater vi;
public NewsAdapter(Context context, int resource, ArrayList<News> objects) {
super(context, resource, objects);
ArrayListNews = objects;
Resourse = resource;
this.context = context;
vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = vi.inflate(Resourse, null);
holder = new ViewHolder();
holder.imageview = (ImageView) convertView.findViewById(R.id.imagenews);
holder.nameNews = (TextView) convertView.findViewById(R.id.namenews);
holder.dayNews = (TextView) convertView.findViewById(R.id.daynews);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
new DownloadImageTask(holder.imageview).execute(ArrayListNews.get(position).getImageNews());
holder.nameNews.setText(ArrayListNews.get(position).getNameNews());
holder.dayNews.setText(ArrayListNews.get(position).getDayNews());
return convertView;
}
static class ViewHolder {
public ImageView imageview;
public TextView nameNews;
public TextView dayNews;
}
//this is i try load image. I using wrong somthing, please help me
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
ImageLoader imgLoader;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
#Override
protected Bitmap doInBackground(String... urls) {
final String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
Handler handler = new Handler(context.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
//this is class on this [link][1]. I try use simple, it work. But here dont work
imgLoader = new ImageLoader(context);
imgLoader.DisplayImage(urldisplay, bmImage);
}
});
} catch (Exception e) {
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
I am trying to update the Main Thread UI after the Async is executed. I've tried to update it via onPostExecute and getting NullPointerException .
Here is my class
public class UncheckGuestArrayAdapter extends ArrayAdapter<UncheckGuestObj> {
private final Activity thisContext;
private ArrayList<UncheckGuestObj> guest = new ArrayList<UncheckGuestObj>();
// String event_id;
private String guest_id;
// TODO to ask about the checkin
static class ViewHolder {
public TextView guestName;
public TextView guestEmail;
public Button btnCheckIn;
}
public ViewHolder holder;
private ViewHolder getHolder(View v) {
ViewHolder holder = new ViewHolder();
holder.guestName = (TextView) v.findViewById(R.id.tx_guest_name);
holder.guestEmail = (TextView) v.findViewById(R.id.tx_guest_email);
holder.btnCheckIn = (Button) v.findViewById(R.id.btnCheckIn);
return holder;
}
public UncheckGuestArrayAdapter(Activity context,
ArrayList<UncheckGuestObj> objects) {
super(context, R.layout.row_guest_list, objects);
this.thisContext = context;
this.guest = objects;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
View vi = convertView;
if (vi == null || vi.getTag() == null) {
LayoutInflater inflater = (LayoutInflater) thisContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi = inflater.inflate(R.layout.row_guest_list, null);
holder = getHolder(vi);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
holder.guestName.setText(guest.get(position).guestName);
holder.guestEmail.setText(guest.get(position).guestEmail);
holder.btnCheckIn.setText("Check In");
// holder.btnCheckIn.setBackgroundColor(Color.GREEN);
holder.btnCheckIn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d("you clicked", "the item at [" + position + "] position");
guest_id = guest.get(position).guestId;
new CheckInAsync().execute();
}
});
return vi;
}
// Check In Async Task for executing the POST Request
public class CheckInAsync extends AsyncTask<Void, Void, Void> {
ProgressDialog mProgressDialog;
#Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(3000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
try {
URI uri = new URI(Constants.BASE_URL + "/events/"
+ GuestListActivity.event_id + "/guests/" + guest_id);
Log.e(getClass().getSimpleName(), uri.toString());
HttpPost httppost = new HttpPost(uri);
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
2);
// nameValuePairs.add(new BasicNameValuePair("sk", SharePref
// .getInstance(GetEventList.this).getSessionKey()));
Context mContext = null;
nameValuePairs.add(new BasicNameValuePair("sk", SharePref
.getInstance(mContext).getSessionKey()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
int response_code = response.getStatusLine().getStatusCode();
// HttpEntity entity = response.getEntity();
Log.i("response code", "" + response_code);
if (response_code == 201) {
Log.e("checkin status", "Checkin done");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
mProgressDialog.dismiss();
holder.btnCheckIn.setText(R.string.heavy_check_mark);
holder.btnCheckIn.setBackgroundColor(Color.MAGENTA);
Toast.makeText(getContext(), "Checked In!", Toast.LENGTH_SHORT)
.show();
}
}
}
And the exception is
08-23 18:56:16.192: E/AndroidRuntime(11077): FATAL EXCEPTION: main
08-23 18:56:16.192: E/AndroidRuntime(11077): java.lang.NullPointerException
08-23 18:56:16.192: E/AndroidRuntime(11077): at com.example.example.adaptor.UncheckGuestArrayAdapter$CheckInAsync.onPostExecute(UncheckGuestArrayAdapter.java:166)
08-23 18:56:16.192: E/AndroidRuntime(11077): at com.example.example.UncheckGuestArrayAdapter$CheckInAsync.onPostExecute(UncheckGuestArrayAdapter.java:1)
08-23 18:56:16.192: E/AndroidRuntime(11077): at android.os.AsyncTask.finish(AsyncTask.java:631)
08-23 18:56:16.192: E/AndroidRuntime(11077): at android.os.AsyncTask.access$600(AsyncTask.java:177)
Line no. 166 is line in onPostExecute
holder.btnCheckIn.setText(R.string.heavy_check_mark);
holder.btnCheckIn.setBackgroundColor(Color.MAGENTA);
What am I doing wrongly ?
The Holder object cannot be a member because it corresponds to one single item. And you are not assigning the member value, instead the local ViewHolder is asigned. Here is how it should work. Remove the ViewHolder member,
public ViewHolder holder;
and
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
// ...
// copy from original post
// ...
holder.btnCheckIn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d("you clicked", "the item at [" + position + "] position");
guest_id = guest.get(position).guestId;
new CheckInAsync(holder).execute();
}
});
return vi;
}
// Check In Async Task for executing the POST Request
public final class CheckInAsync extends AsyncTask<Void, Void, Void> {
private ProgressDialog mProgressDialog;
private final ViewHolder holder;
CheckInAsync(ViewHolder holder) {
this.holder = holder;
}
#Override
protected Void doInBackground(Void... params) {
// copy from original post
}
protected void onPostExecute(Void result) {
this.mProgressDialog.dismiss();
this.holder.btnCheckIn.setText(R.string.heavy_check_mark);
this.holder.btnCheckIn.setBackgroundColor(Color.MAGENTA);
Toast.makeText(getContext(), "Checked In!", Toast.LENGTH_SHORT)
.show();
}
}
I think for your ProgressDialog null and async onPreExecute method override implement and solve for your excepiton,
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = ProgressDialog.show(YourActivityName.this, "wait", "loading");
}
Try the below
ViewHolder holder;
if (vi == null || vi.getTag() == null) {
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) thisContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi = inflater.inflate(R.layout.row_guest_list, null);
holder.guestName = (TextView) v.findViewById(R.id.tx_guest_name);
holder.guestEmail = (TextView) v.findViewById(R.id.tx_guest_email);
holder.btnCheckIn = (Button) v.findViewById(R.id.btnCheckIn);
holder = getHolder(vi);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
.....
Also you need to follow Doctoror Drive suggestion
You do not have reference to the view's. So when you try to update the views in onPostExecute you get NullPointerException.
holder.btnCheckIn.setText(R.string.heavy_check_mark);
holder.btnCheckIn.setBackgroundColor(Color.MAGENTA);
I am creating an android app the UI of my application is below given.
On clicking of submit button, I need the selected check box, value and id textview
example size is not checked, cc(radio button) is checked.
records are populated dynamically in list view, but I am not able to make it work.
Checkbox_ProducoptionActivity.java
public class MainActivity extends Activity implements OnItemClickListener {
ListView listview;
ArrayList<HashMap<String, String>> list_kategori ;
ProgressDialog pd;
ArrayAdapter<Model_checkbox> adapter;
List<String> idprdoptins = new ArrayList<String>();
List<Model_checkbox> nameprdoptn = new ArrayList<Model_checkbox>();
List<Model_checkbox> list = new ArrayList<Model_checkbox>();
Button btn_checkbox;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.checkboxproduct_option);
listview = (ListView)findViewById(R.id.list);
btn_checkbox = (Button)findViewById(R.id.btn_productoption);
// TODO Auto-generated method stub
String id =CheckLogin();
if (id!=""){
loadproductoption(id);
}
btn_checkbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
for (Model_checkbox m : list) {
Log.i("Stack1", m.toString());
}
Log.d("Stack1",String.valueOf(Model_checkbox.class));
Toast.makeText(getApplicationContext(), "ada",Toast.LENGTH_LONG).show();
}
});
}
public void loadproductoption(String id) {
listproduct task= new listproduct();
task.execute(id);
}
private class listproduct extends AsyncTask<String, Void, String>{
protected void onPreExecute(){
pd = new ProgressDialog(Checkbox_ProducoptionActivity.this);
pd.setMessage("Please wait..");
pd.setCancelable(false);
pd.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
JSONObject jsonResult = HttpClientCustom.getRequest(Konfigurasi.strUrl+"api-v1/proop?id_user="+ params[0]);
return jsonResult.toString();
}
protected void onPostExecute(String result){
JSONObject jsonResponse=null;
JSONArray jObject=null;
list_kategori = new ArrayList<HashMap<String, String>>();
try {
jsonResponse = new JSONObject(new String(result));
if(jsonResponse.getString("status").equals("SUCCESS")) {
if (!jsonResponse.getString("total").equals("0")){
jObject = jsonResponse.getJSONArray("resultset");
for (int i = 0; i < jObject.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("idprd", jObject.getJSONObject(i).getString("id"));
map.put("id_user", jObject.getJSONObject(i).getString("id_user"));
map.put("namepd", jObject.getJSONObject(i).getString("name"));
setListnama(jObject.getJSONObject(i).getString("name"));
list_kategori.add(map);
}
adapter = new Adapter_Checkboxproductoption(Checkbox_ProducoptionActivity.this, getModel());
listview.setAdapter(adapter);
}
pd.dismiss();
} else if (jsonResponse.getString("status").equals("FAILED")) {
pd.dismiss();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pd.dismiss();
}
private List<Model_checkbox> getModel() {
return nameprdoptn;
}
public void setListnama(String name) {
nameprdoptn.add(new Model_checkbox(name));
}
}
Model checkbox.java
// public class My modele {
public class Model_checkbox {
private String name;
private boolean selected;
//private boolean isCcOrIsTo;
public Model_checkbox(String name) {
this.name = name;
}
public String getName() {
return name;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
#Override
public String toString() {
String selectedString = selected ? "selected" : "not selected";
// String value = isCcOrIsTo ? "CC" : "To";
return name+" -> "+selectedString+ " with value ";
}
}
MyAdapter.java
// public class MyAdapter extends ArrayAdapter {
class ViewHolder {
protected TextView text;
protected CheckBox checkbox;
}
public class Adapter_Checkboxproductoption extends ArrayAdapter<Model_checkbox> {
private final List<Model_checkbox> list;
private final Activity context;
boolean checkAll_flag = false;
boolean checkItem_flag = false;
public Adapter_Checkboxproductoption(Activity context, List<Model_checkbox> list) {
super(context, R.layout.list_checkbox, list);
this.context = context;
this.list = list;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
convertView = inflator.inflate(R.layout.list_checkbox, null);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) convertView.findViewById(R.id.rowTextView);
viewHolder.checkbox = (CheckBox) convertView.findViewById(R.id.CheckBox01);
viewHolder.checkbox.setTag(position);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.text.setText(list.get(position).getName());
viewHolder.checkbox.setChecked(list.get(position).isSelected());
viewHolder.checkbox.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
CheckBox checkbox = (CheckBox) v;
int getPosition = (Integer) checkbox.getTag();
list.get(getPosition).setSelected(checkbox.isChecked());
}
});
return convertView;
}
}
can't work in "Checkbox_ProducoptionActivity.java"
for (Model_checkbox m : list) {
Log.i("Stack1", m.toString());
Can any body help me in getting value and id of selected check box?
All you need to do is get/set the value of checked item in your adapter this way, I did in Cursor adapter you can update below code as per your need.
public class CursorAdapterList extends CursorAdapter {
private LayoutInflater inflater = null;
private DBAdapter db = null;
private Context ctx = null;
public CursorAdapterList(Context context, Cursor c, DBAdapter database) {
super(context, c);
ctx = context;
db = database;
inflater = LayoutInflater.from(context);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView tv = (TextView) view.findViewById(R.id.txtGameNameInList);
CheckBox favBox = (CheckBox) view.findViewById(R.id.favbuttonInList);
tv.setText(cursor.getString(1));
//here I am getting value of already checked boxes from db
String flag = cursor.getString(3);
if (flag.equals("true")) {
favBox.setChecked(true);
} else {
favBox.setChecked(false);
}
favBox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
LinearLayout parentView = (LinearLayout) v.getParent();
TextView clickedText = (TextView) parentView
.findViewById(R.id.txtGameNameInList);
//here you can get the Item value what your selcted in your list
String name = clickedText.getText().toString();
if (((CheckBox) v).isChecked()) {
Toast.makeText(ctx, name + " is Marked as Favorite Game!!",
Toast.LENGTH_SHORT).show();
//below method will store selected item value in db
db.markAsFavorite(name, "true");
} else {
db.markAsFavorite(name, "false");
}
}
});
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return inflater.inflate(R.layout.list_row_custom, parent, false);
}
}
For my activity
public class Checkbox_ProducoptionActivity<country> extends Activity {
ListView list;
static Context mContext;
Button btnSave;
List<String> val = new ArrayList<String>();
ArrayList<HashMap<String, String>> list_kategori ;
ArrayList<String> stock_list = new ArrayList<String>();
ArrayList<String> stock2_list = new ArrayList<String>();
ProgressDialog pd;
EfficientAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.checkboxproduct_option);
list = (ListView) findViewById(R.id.ListView01);
btnSave = (Button)findViewById(R.id.btnSave);
mContext = this;
final String id =CheckLogin();
if (id!=""){
loadproductoption(id);
}
btnSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SharedPreferences val_shared = getSharedPreferences("CHECKBOX_SHARED", MODE_WORLD_WRITEABLE);
SharedPreferences.Editor cleareditor=val_shared.edit();
cleareditor.clear();
cleareditor.commit();
for (int i = 0; i <list.getCount() ; i++) {
View vListSortOrder;
vListSortOrder=list.getChildAt(i);
try{
TextView textval= (TextView)vListSortOrder.findViewById(R.id.TextView01);
CheckBox ckc=(CheckBox)vListSortOrder.findViewById(R.id.chkbox1);
EditText edit=(EditText)vListSortOrder.findViewById(R.id.txtbox);
if (ckc.isChecked()){
edit.getText().toString();
String temp1 = textval.getText().toString();
Toast.makeText(getApplicationContext(), "fuck"+textval.getText().toString(), Toast.LENGTH_LONG).show();
val.add(temp1);
}
}catch (Exception e) {
// TODO: handle exception
}
}
SharedPreferences customer_ident = getSharedPreferences("CHECKBOX_SHARED", MODE_WORLD_WRITEABLE);
SharedPreferences.Editor editor=customer_ident.edit();
editor.putString("valuecheck", val.toString());
editor.commit();
// Toast.makeText(getApplicationContext(), "ada "+val, Toast.LENGTH_LONG).show();
Intent prdmenuact = new Intent(getApplicationContext(),CreateManageProductActivity.class);
prdmenuact.putExtra("idaction", "1");
startActivity(prdmenuact);
finish();
}
});
}
public void loadproductoption(String id) {
listproduct task= new listproduct();
task.execute(id);
}
private class listproduct extends AsyncTask<String, Void, String>{
protected void onPreExecute(){
pd = new ProgressDialog(Checkbox_ProducoptionActivity.this);
pd.setMessage("Please wait..");
pd.setCancelable(false);
pd.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
JSONObject jsonResult = HttpClientCustom.getRequest(Konfigurasi.strUrl+"api-v1/proop?id_user="+ params[0]);
return jsonResult.toString();
}
protected void onPostExecute(String result){
JSONObject jsonResponse=null;
JSONArray jObject=null;
list_kategori = new ArrayList<HashMap<String, String>>();
try {
jsonResponse = new JSONObject(new String(result));
if(jsonResponse.getString("status").equals("SUCCESS")) {
if (!jsonResponse.getString("total").equals("0")){
jObject = jsonResponse.getJSONArray("resultset");
for (int i = 0; i < jObject.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("idprd", jObject.getJSONObject(i).getString("id"));
map.put("id_user", jObject.getJSONObject(i).getString("id_user"));
map.put("namepd", jObject.getJSONObject(i).getString("name"));
list_kategori.add(map);
}
adapter = new EfficientAdapter(Checkbox_ProducoptionActivity.this,list_kategori );
list.setAdapter(adapter);
}
pd.dismiss();
} else if (jsonResponse.getString("status").equals("FAILED")) {
pd.dismiss();
}
} catch (JSONException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
pd.dismiss();
}
}
my adpater
public class EfficientAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private LayoutInflater inflater=null;
public ImageLoader imageLoader;
String priceprd ;
public EfficientAdapter (Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public EfficientAdapter(Runnable runnable,
ArrayList<HashMap<String, String>> list_kategori) {
// TODO Auto-generated constructor stub
}
public int getCount() {
//Log.d("country",String.valueOf(data.size()));
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_checkbox, parent,
false);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.TextView01);
holder.text2 = (TextView) convertView.findViewById(R.id.TextView02);
holder.txt = (EditText) convertView.findViewById(R.id.txtbox);
holder.cbox = (CheckBox) convertView.findViewById(R.id.chkbox1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText( data.get(position).get("idprd"));
holder.text2.setText(data.get(position).get("namepd"));
holder.txt.setText("");
holder.cbox.setChecked(false);
return convertView;
}
public class ViewHolder {
TextView text;
TextView text2;
EditText txt;
CheckBox cbox;
}
}
public String[] convert(List<String[]> list1) {
// TODO Auto-generated method stub
return null;
}
adapter to be replaced
and the model removed
so to check the value of just using ischecked
for (int i = 0; i <list.getCount() ; i++) {
View vListSortOrder;
vListSortOrder=list.getChildAt(i);
try{
TextView textval= (TextView)vListSortOrder.findViewById(R.id.TextView01);
CheckBox ckc=(CheckBox)vListSortOrder.findViewById(R.id.chkbox1);
EditText edit=(EditText)vListSortOrder.findViewById(R.id.txtbox);
if (ckc.isChecked()){
edit.getText().toString();
String temp1 = textval.getText().toString();
Toast.makeText(getApplicationContext(), "fuck"+textval.getText().toString(), Toast.LENGTH_LONG).show();
val.add(temp1);
}
}catch (Exception e) {
// TODO: handle exception
}
}
and successful