why am i getting nullpointexception on a virtual method onclick listener - onclicklistener

I'm trying to implement a popup window for app, but I guess my implementation is not correct. I'm getting nullpointexception virtual method null object. I guess I'm calling the onclickListener on a null object. what is the correct way to implement the popup window. The window responds to a click on a menu item "about" Any help appreciated.
exception error
Process: com.example.android.droidscanner, PID: 14958
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.android.droidscanner.MainActivity.showAboutWindow(MainActivity.java:152)
at com.example.android.droidscanner.MainActivity.onOptionsItemSelected(MainActivity.java:131)
MainActivity
package com.example.android.droidscanner;
import android.content.Intent;
import android.graphics.Color;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
Button btnReadNet;
TextView textResult;
ListView listViewNode;
ArrayList<String> networkList;
ArrayAdapter<String> adapterNet;
public String ip;
Toolbar myToolbar;
private LayoutInflater popUpInflater;
private PopupWindow popUpWindow;
private Button btnDismiss;
private LinearLayout linearMain;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setting the ActionBar for the activity
myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
btnReadNet = (Button) findViewById(R.id.read_network);
textResult = (TextView) findViewById(R.id.result);
//referencing listview from activity_main.xml
listViewNode = (ListView) findViewById(R.id.nodelist);
networkList = new ArrayList<>();
//referencing LinearLayout in activity_main.xml for popup window
linearMain = (LinearLayout) findViewById(R.id.linearLayout_main);
//inflating the adapter
adapterNet = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, networkList);
listViewNode.setAdapter(adapterNet);
WifiManager wifiMan = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiMan.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
ip = String.format("%d.%d.%d.%d", (ipAddress & 0xff), (ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff));
textResult.setText(printOutput(wifiInfo));
//starting network scanner activity on button press
btnReadNet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent scanNetIntent = new Intent(MainActivity.this, IpScanActivity.class);
scanNetIntent.putExtra("ip", ip);
startActivity(scanNetIntent);
}
});
}
public String printOutput(WifiInfo wifiInfo) {
return "Local IP: " + ip + "\n" +
"SSID: " + wifiInfo.getSSID() + "\n" +
"BSSID: " + wifiInfo.getBSSID() + "\n" +
"MAC: " + wifiInfo.getMacAddress() + "\n" +
"Signal: " + wifiInfo.getRssi() + "db" + "\n" +
"Speed: " + wifiInfo.getLinkSpeed() + "Mbps" + "\n" +
//
"Connection: " + wifiInfo.getSupplicantState();
}
/*
* Infating the menu for toolbar
*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
/*
* actions for menu options in toolbar
*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_ping) {
Intent pingIntent = new Intent(MainActivity.this, PingActivity.class);
startActivity(pingIntent);
return true;
}
if (id == R.id.action_netstat) {
Intent netstatIntent = new Intent(MainActivity.this, NetstatActivity.class);
startActivity(netstatIntent);
return true;
}
if (id == R.id.action_refresh) {
//reload this activity (refresh)
Intent thisActivity = new Intent(this, MainActivity.class);
startActivity(thisActivity);
return true;
}
if (id == R.id.action_about) {
showAboutWindow();
return true;
}
return super.onOptionsItemSelected(item);
}
/*
* method to display about popup window with app informmation
* eg: developer name, version, website
*/
public void showAboutWindow() {
//layout inflater for about popup window
popUpInflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
ViewGroup container = (ViewGroup) popUpInflater.inflate(R.layout.popup_win, null);
popUpWindow = new PopupWindow(container, 500, 500, true);
popUpWindow.showAtLocation(linearMain, Gravity.NO_GRAVITY, 500, 500);
//button reference for popup window dismiss button
btnDismiss = (Button) findViewById(R.id.dismiss);
btnDismiss.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
popUpWindow.dismiss();
}
});
}
}
popup window xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/app_info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DroidScanner by zentech"
android:textSize="18dp"/>
<TextView
android:id="#+id/url_info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="http://pctechtips.org"
android:textSize="18dp"/>
<Button
android:id="#+id/dismiss"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18dp"
android:text="ok" />
</LinearLayout>
</LinearLayout>

Related

OnTabChanged not called when click on current tab

I implemented a tabbed application with Xamarin.Android using TabHost and MvxTabsFragmentActivity.
I want to refresh the current tab when clicking on it the second time.
Is there any method like OnTabReselected from Android?
That's how I am creating the tabs, using TabHost:
<TabHost android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white">
<LinearLayout android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="7dp"
android:background="#drawable/gradient_border_top"
android:orientation="horizontal" />
<TabWidget android:id="#android:id/tabs"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="56dp"
android:layout_weight="0"
android:background="#color/white" />
<FrameLayout android:id="#android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0" />
</LinearLayout>
</TabHost>
And MainView:
[Activity(Theme = "#style/MyTheme", ScreenOrientation = ScreenOrientation.Portrait, WindowSoftInputMode = SoftInput.AdjustPan)]
public class MainView : MvxTabsFragmentActivity
{
public MainView() : base(Resource.Layout.main_layout, Resource.Id.actualtabcontent)
{
}
private static TabHost TabHost { get; set; }
public override void OnTabChanged(string tag)
{
var pos = TabHost.CurrentTab;
var tabView = TabHost.TabWidget.GetChildTabViewAt(pos);
tabView.FindViewById<ImageView>(Resource.Id.tabImage)
.SetColorFilter(new Color(ContextCompat.GetColor(Application.Context, Resource.Color.tabColorSelected)));
tabView.FindViewById<TextView>(Resource.Id.tabTitle)
.SetTextColor(new Color(ContextCompat.GetColor(Application.Context, Resource.Color.tabColorSelected)));
for (var i = 0; i < TabHost.TabWidget.ChildCount; i++)
{
if (pos != i)
{
var tabViewUnselected = TabHost.TabWidget.GetChildTabViewAt(i);
tabViewUnselected.FindViewById<ImageView>(Resource.Id.tabImage)
.SetColorFilter(new Color(ContextCompat.GetColor(Application.Context, Resource.Color.tabColor)));
tabViewUnselected.FindViewById<TextView>(Resource.Id.tabTitle)
.SetTextColor(new Color(ContextCompat.GetColor(Application.Context, Resource.Color.tabColor)));
}
}
base.OnTabChanged(tag);
}
}
// This is where I add all 4 tabs
protected override void AddTabs(Bundle args)
{
AddTab<TrackHomeView>(
args,
Mvx.IoCProvider.IoCConstruct<TrackHomeViewModel>(),
CreateTabFor(((int)TabIdentifier.TrackTab).ToString(), Resource.Drawable.ic_track_icon, Strings.Track));
AddTab<SendView>(
args,
Mvx.IoCProvider.IoCConstruct<SendViewModel>(),
CreateTabFor(((int)TabIdentifier.SendTab).ToString(), Resource.Drawable.ic_send_icon, Strings.Send));
if (MainViewModel.IsUserLoggedIn())
{
AddTab<ProfileView>(
args,
Mvx.IoCProvider.IoCConstruct<ProfileViewModel>(),
CreateTabFor(((int)TabIdentifier.ProfileTab).ToString(), Resource.Drawable.ic_profile_icon, Strings.Profile));
}
else
{
AddTab<CreateAccountView>(
args,
Mvx.IoCProvider.IoCConstruct<CreateAccountViewModel>(),
CreateTabFor(((int)TabIdentifier.ProfileTab).ToString(), Resource.Drawable.ic_profile_icon, Strings.Profile));
}
AddTab<MoreView>(
args,
Mvx.IoCProvider.IoCConstruct<MoreViewModel>(),
CreateTabFor(((int)TabIdentifier.MoreTab).ToString(), Resource.Drawable.ic_more_icon, Strings.More));
}
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
TabHost = FindViewById<TabHost>(global::Android.Resource.Id.TabHost);
TabHost.TabWidget.SetDividerDrawable(null);
TabHost.Setup();
}
I added only relevant code.
The tabs are created using TabHost, and the Activity is inherited from MvxTabsFragmentActivity.
You can inherit the ActionBar.ITabListener interface in your TabHost's MvxTabsFragmentActivity and then you can get the events that you need.
public class MainActivity : MvxTabsFragmentActivity, ActionBar.ITabListener
{
public void OnTabReselected(ActionBar.Tab tab, FragmentTransaction ft)
{
// Optionally refresh/update the displayed tab.
Log.Debug(Tag, "The tab {0} was re-selected.", tab.Text);
}
public void OnTabSelected(ActionBar.Tab tab, FragmentTransaction ft)
{
// Display the fragment the user should see
Log.Debug(Tag, "The tab {0} has been selected.", tab.Text);
}
public void OnTabUnselected(ActionBar.Tab tab, FragmentTransaction ft)
{
// Save any state in the displayed fragment.
Log.Debug(Tag, "The tab {0} as been unselected.", tab.Text);
}
...

Update textview in android custom notification

I have a custom local notification implementing remoteview comprising of three buttons and a textview. Button click in notification changes volume of ringer but I want to increment a variable count each time the up button click or decrement then count each time downbutton click. I have problem updating textview as the broadcaster class can't access it directly. I tried a method from a post, but I can't make it work.
I get null exception at tvUpdate.text=t;
Any idea would be appreaciated. Thanks
RemoteView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="75dp"
android:weightSum="100"
android:padding="5dp"
android:background="#969696"
android:minWidth="25px"
android:minHeight="25px">
<Button
android:text="Vol_Up"
android:layout_width="0dp"
android:layout_weight="25"
android:background="#drawable/roundcnr"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:textColor="#FFFFFF"
android:id="#+id/btnVolUp" />
<Button
android:text="V_Down"
android:layout_width="0dp"
android:layout_weight="25"
android:layout_margin="5dp"
android:textColor="#FFFFFF"
android:background="#drawable/roundcnr"
android:layout_height="wrap_content"
android:id="#+id/btnVolDown" />
<Button
android:text="Silent"
android:layout_width="0dp"
android:layout_weight="25"
android:layout_margin="5dp"
android:background="#drawable/roundcnr"
android:layout_height="wrap_content"
android:textColor="#FFFFFF"
android:id="#+id/btnVolSilent" />
<TextView
android:text="Status"
android:layout_width="0dp"
android:layout_weight="25"
android:textColor="#FFFFFF"
android:layout_height="wrap_content"
android:id="#+id/tvVol" />
</LinearLayout>
Broadcaster Class
namespace RingerTest
{
[BroadcastReceiver]
public class myBroadCastR : BroadcastReceiver
{
public double counter { get; set; }
public override void OnReceive(Context context, Intent intent)
{
if(intent.Action== "VolumeUp")
{
counter += 6;
// Toast.MakeText(context,"VolumeUp",ToastLength.Long).Show();
AudioManager audioManager = (AudioManager)context.GetSystemService(Context.AudioService);
audioManager.AdjustSuggestedStreamVolume(Adjust.Raise, Stream.Ring, VolumeNotificationFlags.PlaySound);
try
{
MainActivity.getinstance().updateTextView(counter.ToString() + "%");
}
catch (Exception ex)
{
}
}
else if (intent.Action == "VolumeDown")
{
counter -= 6;
// Toast.MakeText(context, "VolumeDown",ToastLength.Long).Show();
AudioManager audioManager = (AudioManager)context.GetSystemService(Context.AudioService);
audioManager.AdjustSuggestedStreamVolume(Adjust.Lower, Stream.Ring, VolumeNotificationFlags.PlaySound);
try
{
MainActivity.getinstance().updateTextView(counter.ToString() + "%");
}
catch (Exception ex)
{
}
}
else if (intent.Action == "Silent")
{
counter = 0;
// Toast.MakeText(context, "VolumeDown",ToastLength.Long).Show();
AudioManager audioManager = (AudioManager)context.GetSystemService(Context.AudioService);
audioManager.RingerMode = RingerMode.Silent;
MainActivity.getinstance().updateTextView(counter.ToString()+"%");
}
}
}
}
MainActivity
namespace RingerTest
{
[Activity(Label = "RingerTest", MainLauncher = true)]
public class MainActivity : Activity
{
public static MainActivity ins;
private myBroadCastR myBroadl;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
ins = this;
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
var myreceiver = new myBroadCastR();
var intentfilter = new IntentFilter();
intentfilter.AddAction("VolumeUp");
intentfilter.AddAction("VolumeDown");
intentfilter.AddAction("Silent");
RegisterReceiver(myreceiver, intentfilter);
Button btnNotify = FindViewById<Button>(Resource.Id.button1);
btnNotify.Click += BtnNotify_Click;
}
public static MainActivity getinstance()
{
return ins;
}
public void updateTextView(string t)
{
MainActivity.ins.RunOnUiThread(() =>
{
TextView tvUpdate = FindViewById<TextView>(Resource.Id.tvVol);
tvUpdate.Text = t;
});
}
private void BtnNotify_Click(object sender, System.EventArgs e)
{
const int requestID = 1;
//Volume Up
Intent intent_V_UP = new Intent("VolumeUp");
PendingIntent pIntent_V_UP = PendingIntent.GetBroadcast(this, requestID, intent_V_UP, PendingIntentFlags.UpdateCurrent);
//Volume Down
Intent intent_V_Down = new Intent("VolumeDown");
PendingIntent pIntent_V_Down = PendingIntent.GetBroadcast(this, requestID, intent_V_Down, PendingIntentFlags.UpdateCurrent);
//Silent
Intent intent_Silent = new Intent("Silent");
PendingIntent pIntent_Silent = PendingIntent.GetBroadcast(this, requestID, intent_Silent, PendingIntentFlags.UpdateCurrent);
Notification.Builder builder = new Notification.Builder(this);
builder.SetSmallIcon(Resource.Drawable.addContact);
/*
builder.SetContentTitle("VolControl");
builder.AddAction(Resource.Drawable.addContact, "VolDown", pIntent_V_Down);
builder.AddAction(Resource.Drawable.addContact, "VolUP", pIntent_V_UP);*/
//Custom View for Notification
RemoteViews remoteViews = new RemoteViews(this.PackageName, Resource.Layout.customNotification);
//On Button Click in CustomView
remoteViews.SetOnClickPendingIntent(Resource.Id.btnVolUp, pIntent_V_UP);
remoteViews.SetOnClickPendingIntent(Resource.Id.btnVolDown, pIntent_V_Down);
remoteViews.SetOnClickPendingIntent(Resource.Id.btnVolSilent, pIntent_Silent);
Notification notification = builder.Build();
notification.BigContentView = remoteViews;
notification.Flags = NotificationFlags.NoClear;
NotificationManager notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.Notify(1, notification);
}
}
}

How to find index or information of clicked RadioButton

I was wondering if there was anyway to either find the index when a certain RadioButton is pressed or to pass myBuns.get(i) when the RadioButton. Using the code below to create the RadioButtons
RadioButton rButton;
for (i = 0; i < myBuns.size(); i ++){
rButton = new RadioButton("" + myBuns.get(i));
rButton.setToggleGroup(bunGroup);
rButton.setOnAction(this);
this.getChildren().add(rButton);
}
Thanks for any help or suggestions!
You can get the index of the selected toggle using:
toggleGroup.getToggles().indexOf(toggleGroup.getSelectedToggle());
And the text of the selected toggle using:
((RadioButton) toggleGroup.getSelectedToggle()).getText();
By placing the code in the change listener for the selected toggle property, you can monitor when the selected toggle changes and take action as appropriate.
Sample App
import javafx.application.Application;
import javafx.collections.*;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import java.util.stream.*;
public class ToggleIndexer extends Application {
#Override
public void start(final Stage stage) throws Exception {
ToggleGroup toggleGroup = new ToggleGroup();
ObservableList<RadioButton> buttons = IntStream.range(0, 5)
.mapToObj(i -> new RadioButton("Radio " + i))
.collect(Collectors.toCollection(FXCollections::observableArrayList));
toggleGroup.getToggles().setAll(buttons);
Label selectedIndex = new Label();
selectedIndex.setFont(Font.font("monospace"));
Label selectedItem = new Label();
selectedItem.setFont(Font.font("monospace"));
toggleGroup.selectedToggleProperty().addListener((observable, oldValue, newValue) -> {
if (newValue == null) {
selectedIndex.setText("");
selectedItem.setText("");
} else {
final int selectedIndexValue =
toggleGroup.getToggles().indexOf(newValue);
selectedIndex.setText("Selected Index: " + selectedIndexValue);
final String selectedItemText =
((RadioButton) toggleGroup.getSelectedToggle()).getText();
selectedItem.setText( "Selected Item: " + selectedItemText);
}
});
VBox layout = new VBox(8);
layout.setPadding(new Insets(10));
layout.setPrefWidth(250);
layout.getChildren().setAll(buttons);
layout.getChildren().addAll(selectedItem, selectedIndex);
stage.setScene(new Scene(layout));
stage.show();
}
public static void main(String[] args) throws Exception {
launch(args);
}
}

Error in else value on android

i want to change visibility when special status
so i do else like that
else {
ImageView image_A_wrong = (ImageView)findViewById(R.id.imageView1);
image_A_wrong.setVisibility(View.GONE);
}
But appear error on eclipse.
Do you know why ?
my imageview
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/quo100px"
android:visibility="gone" />
Tks advance all
Here my complete file
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.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class quoPAPIERCORD 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_quo = >"http://192.168.1.81/php/android/get_all_quotidiens.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";
private static final String TAG_PRICE = "price";
private static String TAG_CU = "cu";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.quotidiens);
// 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(quoPAPIERCORD.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_quo, >"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);
String price = c.getString(TAG_PRICE);
String cu = c.getString(TAG_CU);
/////////////
if (cu.equals("1")) {
cu = "oui";
} else {
ImageView image_A_wrong = (ImageView) >findViewById(R.id.imageView1);
image_A_wrong.setVisibility(View.GONE);
}
// 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);
map.put(TAG_PRICE, price);
map.put(TAG_CU, cu);
// 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(
quoPAPIERCORD.this, productsList,
R.layout.list_item, new String[] { >TAG_PID,
TAG_NAME, >TAG_PRICE, TAG_CU},
new int[] { R.id.pid, R.id.name, >R.id.price, R.id.cu });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5px"
android:stretchColumns="1">
<!-- Product id (pid) - will be HIDDEN - used to pass to other activity -->
<TextView
android:id="#+id/pid"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone" />
<!-- Name Label -->
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingRight="10px"
android:textSize="17sp"
android:layout_marginRight="10px"
android:layout_weight="0.2"
android:textColor="#fff"
android:gravity="left" />
<!-- price Label -->
<TextView
android:id="#+id/price"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingRight="5px"
android:textSize="17sp"
android:layout_marginRight="5px"
android:layout_weight="0.2"
android:textColor="#C00000"
android:gravity="left"
android:textStyle="bold" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/quo100px"/>
<TextView
android:id="#+id/cu"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingRight="5px"
android:textSize="17sp"
android:layout_marginRight="5px"
android:layout_weight="0.2"
android:textColor="#C00000"
android:gravity="left"
android:textStyle="bold" />
<TextView
android:id="#+id/mc"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingRight="5px"
android:textSize="17sp"
android:layout_marginRight="5px"
android:layout_weight="0.2"
android:textColor="#C00000"
android:gravity="left"
android:textStyle="bold" />
<TextView
android:id="#+id/tel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingRight="5px"
android:textSize="17sp"
android:layout_marginRight="5px"
android:layout_weight="0.2"
android:textColor="#C00000"
android:gravity="left"
android:textStyle="bold" />
</LinearLayout>
Seeing your error here, You can't access UI (Textview, Edittext, ImageView, etc) inside DoInBackgroud. Do it on either OnPostExecute or OnProgressUpdate method
Edit: Change this
if (cu.equals("1"))
{
cu = "oui";
}
else
{
ImageView image_A_wrong = (ImageView) findViewById(R.id.imageView1);
image_A_wrong.setVisibility(View.GONE);
}
to
if (cu.equals("1"))
{
cu = "oui";
}
else
{
cu = "pas";
}
then add this to your OnPostExecute()
Edit 2: Seeing your code I've somewhat narrowed your error. the above code must be like
Declare the string cu globally and then try the follwing
ImageView image_A_wrong = (ImageView) findViewById(R.id.imageView1);
if(cu.equals("pas"))
{
image_A_wrong.setVisibility(View.GONE);
}
else
{
image_A_wrong.setVisibility(View.GONE);
}

Android: implementing Checkbox List with ListFragment and ArrayAdapter

I am converting a working application to Fragments. My checkbox list is not displaying the labels, and I am guessing, the id's. I am new to Android/Java and this is my first post to Stackoverflow, so apologies if the question is simple or not following correct protocol.
My ListFragment is as follows:
import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
public class DistributionTransFragment extends ListFragment {
protected TextView subheader;
protected Context mContext;
protected DatabaseHandler db;
protected String user_id;
protected String user;
protected String recipients;
protected int number;
protected LayoutInflater inflater;
protected View v;
DistributionArrayAdapter dataAdapter = null;
public DistributionTransFragment(){
super();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.distribution_fragment, container, false);
mContext = getActivity().getApplicationContext();
db = new DatabaseHandler(mContext);
subheader = (TextView)v.findViewById(R.id.textView2);
subheader.setText("Spent On?");
displayListView();
checkButtonClick();
return v;
}
private void displayListView() {
ArrayList<Participant> distributionList = new ArrayList<Participant>();
Participant participant;
List<User> users = db.getAllUsers();
for (User u : users) {
user_id = String.valueOf(u.getID());
user = u.getUser();
participant = new Participant(user_id, user, false);
distributionList.add(participant);
}
//create an ArrayAdaptar from the String Array
dataAdapter = new DistributionArrayAdapter(mContext, R.layout.distributionlist, distributionList);
setListAdapter(dataAdapter);
}
private class DistributionArrayAdapter extends ArrayAdapter<Participant> {
private ArrayList<Participant> distributionList;
public DistributionArrayAdapter(Context context, int textViewResourceId, ArrayList<Participant> distributionList) {
super(context, textViewResourceId, distributionList);
this.distributionList = new ArrayList<Participant>();
this.distributionList.addAll(distributionList);
}
private class ViewHolder {
TextView code;
CheckBox name;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.distributionlist, null);
holder = new ViewHolder();
holder.code = (TextView) convertView.findViewById(R.id.code);
holder.name = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
Log.d("HOLDER CODE", (holder.code).toString());
holder.name.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v ;
Participant participant = (Participant) cb.getTag();
participant.setSelected(cb.isChecked());
}
});
} else {
holder = (ViewHolder) convertView.getTag();
}
Participant participant = distributionList.get(position);
holder.name.setText(participant.getName());
holder.name.setChecked(participant.isSelected());
holder.name.setTag(participant);
return convertView;
}
}
private void checkButtonClick() {
Button myButton = (Button) v.findViewById(R.id.button1);
myButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final ArrayList<Participant> distributionList = dataAdapter.distributionList;
// Do Stuff
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setMessage(tempTransaction);
builder.setCancelable(false);
builder.setPositiveButton("Commit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Do More Stuff
Intent intent = new Intent(mContext, Home.class);
startActivity(intent);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Do Other Stuff
Intent intent = new Intent(mContext, Home.class);
startActivity(intent);
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
}
My XML for the list is as follows:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#color/white"
android:padding="15dip" >
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:focusable="false"
android:focusableInTouchMode="false" />
<TextView
android:id="#+id/code"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/checkBox1"
android:layout_alignBottom="#+id/checkBox1"
android:layout_toRightOf="#+id/checkBox1"
android:textSize="15sp" />
</RelativeLayout>
My XML for the fragment is as follows:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/grey">
<RelativeLayout
android:id="#+id/subheader"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/secondheader"
android:orientation="vertical" >
<TextView
android:id="#+id/textView2"
style="#style/subheader" />
<TextView
android:id="#+id/textView3"
style="#style/info" />
</RelativeLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/subheader"
android:layout_above="#+id/footer"
android:orientation="vertical" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:id="#id/footer"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#color/grey"
android:layout_alignParentBottom="true" >
<Button
android:id="#+id/button1"
style="#style/button.form"
android:text="#string/moneyspent" />
</LinearLayout>
</RelativeLayout>
Any help would be greatly appreciated.
I nutted it out, so thought I would post my answer in case others have the same problem. It was my context. It should have been:
mContext = getActivity();

Resources