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);
}
Related
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);
}
}
}
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>
What I want to do is Create a Single Row Listview/List with a image and text is this is what i have right now
I have Changed the numColumns to 1 but how do I change it so it is Horizontal and Scrollable? the image should be one top and the text should be below it?
This is the Layout
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="90dp"
android:numColumns="1"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
Single Grid Item
<?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="wrap_content">
<ImageView
android:layout_width="match_parent"
android:layout_height="250dp"
android:scaleType="centerCrop"
android:id="#+id/my_image_vieww" />
<TextView
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/my_text_view" />
</LinearLayout>
Main Activity
var gridview = FindViewById<GridView> (Resource.Id.gridview);
gridview.Adapter = new ImageAdapter (this);
gridview.ItemClick += delegate (object sender, AdapterView.ItemClickEventArgs args) {
Toast.MakeText (this, args.Position.ToString (), ToastLength.Short).Show ();
};
public class ImageAdapter : BaseAdapter
{
Context context;
public ImageAdapter (Context c)
{
context = c;
}
public override int Count {
get { return thumbIds.Length; }
}
public override Java.Lang.Object GetItem (int position)
{
return null;
}
public override long GetItemId (int position)
{
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public override View GetView (int position, View convertView, ViewGroup parent)
{
ImageView imageView;
View view;
if (convertView == null) { // if it's not recycled, initialize some attributes
view = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.my_grid_row, parent, false);
} else {
view = convertView;
}
var imageView2 = view.FindViewById<ImageView>(Resource.Id.my_image_vieww);
imageView2.SetImageResource (thumbIds[position]);
var textView = view.FindViewById<TextView>(Resource.Id.my_text_view);
textView.Text = "Text to Display";
return view;
}
}
Please Dont user horizontal list view.
There is predefined android controll to achieve this. View Pager
Sample Code:
var _viewPager = view.FindViewById<ViewPager>(Resource.Id.viewPager);
var _viewPageIndicatorCircle = view.FindViewById<CirclePageIndicator>(Resource.Id.viewPageIndicator);
_viewPager.Adapter = new TestFragmentAdapter(fm);
_viewPageIndicatorCircle.SetViewPager(_viewPager);
public class TestFragmentAdapter : FragmentPagerAdapter
{
public TestFragmentAdapter(Android.Support.V4.App.FragmentManager fm)
: base(fm)
{
}
public override Android.Support.V4.App.Fragment GetItem(int position)
{
return new TestFragment();
}
public override int Count
{
get
{
return 5;
}
}
}
class TestFragment : Android.Support.V4.App.Fragment
{
public TestFragment()
{
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var view = inflater.Inflate(Resource.Layout.MyViewPager , container, false);
return view;
}
}
Viewpager.xml
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="fill_parent"
android:layout_height="209.6dp" />
If you have any queries please feel free to ask me
I am developing a chat application using socketIO library. Every thing seems to work fine except the UI updation. I am able to send message to the port and receive from it. But after reception, i cant update textview or any other UI. the code is given below
Any help is most appreciated
NB: the toast is coming, the **updated* message is also showing when next new message comes
chatRoomActivity.java
public class chatRoomActivity extends Activity implements OnClickListener{
int channelId = 0;
public final String SocketURL = "someURL";
String userName = "";
int connectioAttempt = 0;
SocketIOClient socketClient = null;
SocketIOClientOperations sioOps = null;
Button chatRoomSend = null;
EditText chatInput = null;
TextView msgcntr;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_room);
chatRoomSend = (Button)findViewById(R.id.chatRoomSendBtn);
chatInput = (EditText)findViewById(R.id.chatRoomInput);
msgcntr=(TextView)findViewById(R.id.textView1);
chatRoomSend.setOnClickListener(this);
sioOps = new SocketIOClientOperations();
msgcntr = (TextView) findViewById(R.id.textView1);
socketClient = sioOps.connectToSocket(SocketURL);
System.out.println("**********Connected**********");
if(socketClient != null)
{
boolean joined = false;
joined = sioOps.joinChannel(socketClient, channelId);
System.out.println("*******Joined*********");
}
else
{
System.out.println("*******Null*********");
}
socketClient.on("incomingMessage", new EventCallback() {
public void onEvent(JSONArray argument, Acknowledge acknowledge) {
System.out.println("***************New Message*********");
System.out.println("***************"+argument.toString()+"*********");
msgcntr.setText("test");
updateClock();
}
});
}
#Override
public void onClick(View v) {
if(v == chatRoomSend)
{
boolean sent = sioOps.sendNewMessage(socketClient, userName, "empty");
if(sent)
System.out.println("************** Message Sent *********");
else
System.out.println("************** Message Failed *********");
}
}
protected void updateClock() {
runOnUiThread(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(), "end", Toast.LENGTH_SHORT).show();
msgcntr.setText("test");
System.out.print("************Updated*********");
}
});
}
}
socketIOClientOperations.java
public class SocketIOClientOperations {
public SocketIOClientOperations(){}
public SocketIOClient connectToSocket(String SocketURL)
{
SocketIORequest connectionRequest = new SocketIORequest(SocketURL);
SocketIOClient socketClient = null;
try {
socketClient = SocketIOClient.connect(AsyncHttpClient.getDefaultInstance(), connectionRequest, null).get();
} catch (InterruptedException e) {
e.printStackTrace();
return null;
} catch (ExecutionException e) {
e.printStackTrace();
return null;
}
return socketClient;
}
public boolean joinChannel(SocketIOClient client,int channelId)
{
JSONArray joinChannel = new JSONArray();
JSONObject values = new JSONObject();
try {
values.put("channelID", channelId);
joinChannel.put(values);
client.emit("joinChannel", joinChannel);
return true;
} catch (JSONException e) {
e.printStackTrace();
return false;
}
}
public boolean sendNewMessage(SocketIOClient client,String name,String txt)
{
JSONArray newMsg = new JSONArray();
JSONObject msgBody = new JSONObject();
try {
msgBody.put("From", name);
msgBody.put("Content", txt);
newMsg.put(msgBody);
client.emit("newMessage", newMsg);
System.out.println("***************SendMessage*********");
System.out.println("************** "+newMsg.toString()+" *********");
return true;
} catch (JSONException e) {
e.printStackTrace();
return false;
}
}
}
chat_room.xml
<?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:orientation="vertical" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="40dp"
android:background="#000"
android:padding="10dp"
android:id="#+id/header">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Chat Room"
android:textColor="#fff"
android:textSize="14sp"/>
</RelativeLayout>
<ListView
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:stackFromBottom="true"
android:layout_above="#+id/footer"
android:layout_below="#+id/header"
android:id="#+id/chatRoomMsgs"
android:background="#cccccc"
android:visibility="gone" />
<TextView
android:id="#+id/msgConatainer"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#+id/fooer"
android:layout_below="#+id/header"
android:background="#ccc"
android:textColor="#000" />
<RelativeLayout
android:id="#+id/fooer"
android:background="#000"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:layout_alignParentBottom="true">
<EditText
android:id="#+id/chatRoomInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter your message...."
android:layout_toLeftOf="#+id/chatRoomSendBtn"
android:layout_alignParentLeft="true"/>
<Button
android:id="#+id/chatRoomSendBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send"
android:layout_alignParentRight="true" />
</RelativeLayout>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/msgConatainer"
android:layout_centerHorizontal="true"
android:layout_marginBottom="48dp"
android:text="TextView"
android:textColor="#android:color/black" />
</RelativeLayout>
Try this way
private Handler mHandler = new Handler();
mHandler.post(new Runnable() {
public void run() {
msgcntr.setText("test");
}
});
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();