java.lang.NullPointerException when I'm trying to make button invisible - android

This method works fine.
public void onClick(View view) {
btn = (Button) findViewById(R.id.trytogetin);
progr = (ProgressBar) findViewById(R.id.progressBar);
btn.setVisibility(View.INVISIBLE);
progr.setVisibility(View.VISIBLE);
EditText login = (EditText) findViewById(R.id.loginfld);
EditText passw = (EditText) findViewById(R.id.passfld);
String logincmd = "CheckLogin*" + login.getText() + "*" + passw.getText() + "*";
ss.senddata(logincmd, 1);
}
In this method java.lang.NullPointerException appears (on btn.setVisibility(View.VISIBLE);
public void geturdata(String answer) {
if (answer != null)
{
System.out.println("true");
btn.setVisibility(View.VISIBLE);
}
else
{
System.out.println("false");
}
}
Please tell me how can I call button in this method? Also I can't use StartActivity(intent) in this method.(same error). Both metods placed in one activity.
Here is full code
This is activity
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.content.Intent;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
public class Login extends Activity {
SocketServer ss = new SocketServer();
Button btn;
ProgressBar progr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btn = (Button) findViewById(R.id.trytogetin);
progr = (ProgressBar) findViewById(R.id.progressBar);
try {
ss.setserver();
} catch (Exception ex) {
System.out.println("------- " + ex);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
menu.add("menu1");
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onClick(View view) {
btn.setVisibility(View.INVISIBLE);
progr.setVisibility(View.VISIBLE);
EditText login = (EditText) findViewById(R.id.loginfld);
EditText passw = (EditText) findViewById(R.id.passfld);
String logincmd = "CheckLogin*" + login.getText() + "*" + passw.getText() + "*";
ss.senddata(logincmd, 1);
}
public void geturdata(String answer) {
if (answer != null)
{
System.out.println("true");
btn.setVisibility(View.VISIBLE);
}
else
{
System.out.println("false");
}
}
}
And this is class that call >geturdata
import android.os.Looper;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class SocketServer {
private Socket socket;
private static final int SERVERPORT = 11000;
private static String SERVER_IP = "192.168.2.222";
String answer;
private static String cmdtext;
private static int caller;
class ClientThread implements Runnable
{
public void run() {
if (cmdtext.equals("setserver"))
{
try
{
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
}
catch (Exception ex)
{System.out.println(ex);}
}
else {
try {
String str = cmdtext;
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
out.println(str);
out.flush();
byte[] data = new byte[256];
InputStream inp = socket.getInputStream();
inp.read(data);
answer = new String(data, "UTF-8");
Looper.prepare();
handledata(answer);
Looper.loop();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
////////////////////////////////////////
public void setserver ()
{
new Thread(new ClientThread()).start();
cmdtext = "setserver";
}
private void handledata(String answer)
{
switch (caller) {
case 1:
{
Login lgn = new Login();
lgn.geturdata(answer);
}
}
}
public void senddata(String cmd, int callerid)
{
this.cmdtext = cmd;
this.caller = callerid;
new Thread(new ClientThread()).start();
}
}

btn is null when you call geturdata(). You should call btn = (Button) findViewById(R.id.trytogetin); directly after setContentView(R.layout.activity_main); in public void onCreate(Bundle b)
private Button btn;
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.trytogetin);
...
}
EDIT:
But, seeing your code now, thats not the problem. There are two problems here
Login lgn = new Login();
lgn.geturdata(answer);
You try to instantiate an Activity. You should start activities through intents, so that they are instanciated in the normal Activity lifecycle: through onCreate.
But there's more: You try to set the Button from another Thread than the one which created the Button (the UI-thread)
You can try to get a handle from the context in the thread, and call context.runOnUiThread(Runnable). That way you can update the UI from other Threads.
So the NPE is caused by the fact that you instantiate Login (which has to be done by Android), and call a method, but theres no ContentView inflated, so the Button is not found anyway, findViewById returns null

You are getting id of button inside click method. So to solve the problem , get your button id in oncreate() method. So you can access button anywhere. But declare button globaly

Declare this in OnCreate()
btn = (Button) findViewById(R.id.trytogetin);
progr = (ProgressBar) findViewById(R.id.progressBar);
public void onClick(View view) {
btn.setVisibility(View.INVISIBLE);
progr.setVisibility(View.VISIBLE);
}
String logincmd = "CheckLogin*" + login.getText().toString() + "*" + passw.getText().toString() + "*";
So reference to this method geturdata where you used object of Button btn returns null, since you used inside onClick button.
public void geturdata(String answer) {

Related

TextView is not being updated

I am facing a problem, I have implemented a code, it is showing me message in Logs correctly but it doesn't update the TextView's text. Here i have tried this version. How i can update it? I tried it using threads as well but in vain.
I have seen many solution over this StackOverflow platform but i could not find my any solution for my problem.
package com.example.yousafmoh.seizuredetection;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.AsyncTask;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
public class ledControl extends AppCompatActivity {
// Button btnOn, btnOff, btnDis;
ImageButton On, Off, Discnt, Abt;
TextView txtMessage;
String address = null;
private ProgressDialog progress;
BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
//SPP UUID. Look for it
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent newint = getIntent();
address = newint.getStringExtra(DeviceList.EXTRA_ADDRESS); //receive the address of the bluetooth device
//view of the ledControl
setContentView(R.layout.activity_led_control);
//call the widgets
On = (ImageButton)findViewById(R.id.on);
Off = (ImageButton)findViewById(R.id.off);
Discnt = (ImageButton)findViewById(R.id.discnt);
Abt = (ImageButton)findViewById(R.id.abt);
txtMessage = (TextView) findViewById(R.id.txtMessage);
new ConnectBT().execute(); //Call the class to connect
//myBluetoothThread();
//commands to be sent to bluetooth
On.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
turnOnLed(); //method to turn on
}
});
Off.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
turnOffLed(); //method to turn off
}
});
Discnt.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Disconnect(); //close connection
}
});
}
private void myBluetoothThread() {
while(true)
{
if (btSocket!=null)
{
try
{
if(isBtConnected) {
InputStream inputStream = btSocket.getInputStream();
for (int i = 0; i <= inputStream.available(); i++) {
//Log.d("data", inputStream.read() + " "+"ok");
int val = inputStream.read();
if (val == 49) // seizure detected
{
this.runOnUiThread(new Runnable() {
#Override
public void run() {
txtMessage.setText("Seizure Detected!!!");
txtMessage.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
Log.d("Message", " Detected");
}
});
Log.d("Message", " Detected");
} else if (val == 48) // no detection
{
this.runOnUiThread(new Runnable() {
#Override
public void run() {
txtMessage.setText("Normal Condition");
txtMessage.setTextColor(getResources().getColor(android.R.color.holo_blue_dark));
Log.d("Message", "not Detected");
}
});
Log.d("Message", "not Detected");
//, Toast.LENGTH_SHORT).show();
}
}
}
}
catch (IOException e)
{
msg("Error");
}
}
}
}
private void Disconnect()
{
if (btSocket!=null) //If the btSocket is busy
{
try
{
btSocket.close(); //close connection
}
catch (IOException e)
{ msg("Error");}
}
finish(); //return to the first layout
}
private void turnOffLed()
{
if (btSocket!=null)
{
try
{
InputStream inputStream = btSocket.getInputStream();
for(int i = 0 ; i <= inputStream.available();i++)
{
Log.d("data",inputStream.read()+" ");
}
Log.d("Bytes available off",String.valueOf(inputStream.available()));
Log.d("Message off",String.valueOf(inputStream.read()));
//btSocket.getOutputStream().write("0".toString().getBytes());
}
catch (IOException e)
{
msg("Error");
}
}
}
private void turnOnLed()
{
if (btSocket!=null)
{
try
{
InputStream inputStream = btSocket.getInputStream();
Log.d("Bytes available on",String.valueOf(inputStream.available()));
Log.d("Message on",String.valueOf(inputStream.read()));
Log.d("Message on",inputStream.toString());
btSocket.getOutputStream().write("1".toString().getBytes());
}
catch (IOException e)
{
msg("Error");
}
}
}
// fast way to call Toast
private void msg(String s)
{
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
}
public void about(View v)
{
if(v.getId() == R.id.abt)
{
Intent i = new Intent(this, AboutActivity.class);
startActivity(i);
}
}
#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_led_control, menu);
return true;
}
#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_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class ConnectBT extends AsyncTask<Void, Void, Void> // UI thread
{
private boolean ConnectSuccess = true; //if it's here, it's almost connected
#Override
protected void onPreExecute()
{
progress = ProgressDialog.show(ledControl.this, "Connecting...", "Please wait!!!"); //show a progress dialog
}
#Override
protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background
{
try
{
if (btSocket == null || !isBtConnected)
{
myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);//connects to the device's address and checks if it's available
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();//start connection
progress.dismiss();
}
}
catch (IOException e)
{
ConnectSuccess = false;//if the try failed, you can check the exception here
}
return null;
}
#Override
protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
{
super.onPostExecute(result);
if (!ConnectSuccess)
{
msg("Connection Failed. Is it a SPP Bluetooth? Try again.");
finish();
}
else
{
msg("Connected.");
isBtConnected = true;
}
if(progress!=null)
progress.dismiss();
if(isBtConnected)
{
myBluetoothThread();
}
}
}
}
Try using this if its a fragment class
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
txtMessage.setText("Normal Condition");
txtMessage.setTextColor(getResources().getColor(android.R.color.holo_blue_dark));
}
});
and this is its an activity
this.runOnUiThread(new Runnable() {
#Override
public void run() {
txtMessage.setText("Normal Condition");
txtMessage.setTextColor(getResources().getColor(android.R.color.holo_blue_dark));
}
});
Another solution u can try is.
You can use handler
Handler handler = new Handler();
handler.post(new Runnable() {
public void run() {
txtMessage.setText("Seizure Detected!!!");
txtMessage.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
}
});
I have read some article somewhere that you should not update your textview directly inside the Runnable Thread. So what I did is i created a function that updates the textview then the Runnable run method calls that function. So It look like this.
public class SampleActivity extends AppCompatActivity {
TextView sample;
int counter = 0;
Handler handler;
Runnable runnable;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sample);
sample = findViewById(R.id.sample);
handler = new Handler();
runnable = new Runnable() {
#Override
public void run() {
counter++;
updateTextView("Counter: " + counter);
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(runnable, 1000);
}
public void updateTextView(String message) {
sample.setText(message);
}
But I tried it calling the sample.setText("Counter: "+counter) inside the Runnable Thread, it still works though.
Btw here is my sample.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/sample"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="SAWSAW"
android:textColor="#000"
android:textSize="32dp" />
</LinearLayout>

HttpURLConnection method empty when called

I'm calling a
(getData()
that should run HttpURLConnection and return a string (later to be casted as Long), the string should be the one line from this URL:
https://blockchain.info/tobtc?currency=USD&value=1
Trying to see if it is returning anything , I'm displaying the returned string in the layout.xml file and showing a toast. But both both show as blank
Please do not pay attention to the fact that I'm doing this on the main thread, I'm just trying to make it work first.
What I'm I doing wrong? why it's not returning the string value.
thanks
package app.com.cryptosudan.android.cryptosudan;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton sdg = (ImageButton) findViewById(R.id.imagesdg);
ImageButton btc = (ImageButton) findViewById(R.id.imagebtc);
final TextView display = (TextView) findViewById(R.id.display);
String price;
price = (getData());
display.setText(price);
Toast.makeText(this, price, Toast.LENGTH_LONG).show();
sdg.setOnClickListener(sdgpage);
btc.setOnClickListener(btcpage);
}
//to create an instance of button OnClickListener
View.OnClickListener sdgpage = new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, CalculateSdg.class));
}
};
//to create an instance of button OnClickListener
View.OnClickListener btcpage = new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, CalculateBtc.class));
}
};
public static String getData () {
BufferedReader reader = null;
try {
URL url = new URL("https://blockchain.info/tobtc?currency=USD&value=1");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while((line = reader.readLine()) !=null) {
sb.append (line + "/n");
} return sb.toString();
}catch (Exception e){
e.printStackTrace();
return null;
}finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
}
#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_main, menu);
return true;
}
#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_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
For http request on main thread change you onCreate method with StrictMode.ThreadPolicy.Builder().permitAll()
I Don't recommend Http request in main thread !!!!
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton sdg = (ImageButton) findViewById(R.id.imagesdg);
ImageButton btc = (ImageButton) findViewById(R.id.imagebtc);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
final TextView display = (TextView) findViewById(R.id.display);
String price;
price = (getData());
display.setText(price);
Toast.makeText(this, price, Toast.LENGTH_LONG).show();
sdg.setOnClickListener(sdgpage);
btc.setOnClickListener(btcpage);
}

Eclipse Android App using JSoup, always ending within the Catch

I have some code that uses JSoup and connects to a website successfully in JAVA.
I am trying to duplicate the exact same thing (as a learning experience) on the Android.
I am using Eclipse.
Within my activity_main.xml I have 3 buttons and a text field.
I do not have any errors within my JAVA code and have confirmed it still works within JAVA (running in Netbeans)
I have my JSoup jar within the libs folder ~ that was an issue that took a little while to find.
I have placed some editText.setText(“Here”); to see where the code gets.
I have a message immediately below my doc = JSoup.connect(“http://www.Google.com”).get();
I never get that message.
Likewise I have the same message within my catch routine – I am always getting into the catch routine, meaning I have a problem.
I have tried this two ways – with the android emulator and with my phone attached through the USB cable. I get the same result – the “app” runs fine but displays the message found within the catch{}.
I am at a loss since the exact code works fine within Netbeans / regular JAVA.
Here is my code:
package com.example.duckriver;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.jsoup.helper.Validate;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
int counter;
Button Button1;
Button SummaryStats;
TextView display;
TextView editText;
String dataread = null;
String high = "High:";
String low = "Low:";
String filename = null;
int index = 0;
int startindex = 0;
int lastindex = 0;
int length = 0;
char[] CharArray = new char[1000];
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
counter = 0;
Button1 = (Button) findViewById(R.id.button1);
SummaryStats = (Button) findViewById(R.id.buttonSummaryStats);
display = (TextView) findViewById(R.id.tvMainDisplay);
editText = (TextView) findViewById(R.id.editText);
Button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
//counter++;
Document doc;
try{
doc=Jsoup.connect("http://www.Google.com").get();
editText.setText("Here");
//get Title
//String title = doc.title();
//System.out.println("Title: "+title);
//dataread = doc.body().text(); // "An example link"
Element link = null;
}//end try
catch(Exception ex){
ex.printStackTrace();
editText.setText("Error");
//((TextView)findViewById(R.id.tv)).setText("Error");
}// end catch
}
});
SummaryStats.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
counter = counter*counter;
}
});
return true;
}
}
I am at a loss. Help?
Thanks.
You need download document with Asyncronous task or Android will throw exception. Try this:
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
counter = 0;
Button1 = (Button) findViewById(R.id.button1);
SummaryStats = (Button) findViewById(R.id.buttonSummaryStats);
display = (TextView) findViewById(R.id.tvMainDisplay);
editText = (TextView) findViewById(R.id.editText);
Button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
downloadDocTask task = new downloadDocTask();
task.execute("www.google.com");
}
});
SummaryStats.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
counter = counter*counter;
}
});
return true;
}
private class downloadDocTask extends AsyncTask<String, Void, Document>{
String urldisplay;
#Override
protected Document doInBackground(String... urls) {
urldisplay = urls[0];
Document doc = null;
try {
doc = Jsoup.connect(urldisplay).timeout(10*1000).get();
} catch (IOException e) {
e.printStackTrace();
}
return doc;
}
#Override
protected void onPostExecute(Document result) {
if(result != null){
Log.i(TAG, "downloadDocTask.onPostExcecute Document Download complete");
buildHtml(result);
}
else{
Log.i(TAG, "downloadDocTask.onPostExcecute Document == null");
}
}
}
public void buildHtml(Document doc){
// Parse document here
String title = doc.title();
}

setOnClickListener and findByViewId

this part of my code is having a problem
insertButton = (Button) findByViewId(R.id.button1);
insertButton.setOnClickListener(new OnClickListener();
it keeps saying method undefined for findByViewId, method for setOnClickListener not applicable and OnClickListener cannot be resolved
here is my full code
package edu.nyp.project;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class AddData extends Activity {
Button insertButton = null;
EditText shopText= null;
EditText dealText= null;
EditText locationText= null;
EditText websiteText= null;
EditText categoryText= null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.adddata);
insertButton = (Button) findByViewId(R.id.button1);
insertButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
DBAdapter dbAdapter = new
DBAdapter(getApplicationContext());
try{
dbAdapter.open();
String shop = shopText.getText().toString();
String deal = dealText.getText().toString();
String location = locationText.getText().toString();
String website = websiteText.getText().toString();
String category = categoryText.getText().toString();
}
catch(Exception e){
Log.d("Add Data ", e.getMessage());
}
finally{
if (dbAdapter != null)
dbAdapter.close();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.adddata, menu);
return true;
}
}
may i know what is wrong?
Import below line in your activity
import android.view.View.OnClickListener;
try
insertButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
}
}
Use findViewById method instead of findByViewId.
insertButton = (Button) findViewById(R.id.button1);
insertButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
//Code for action listener.
}
});
Only thing that i can find unusual about the above code is :
insertButton = (Button) findByViewId(R.id.button1);
So replace it with:
insertButton = (Button) findViewById(R.id.button1);
The rest of the code is fine. I mean the below code is perfectly fine:
insertButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
DBAdapter dbAdapter = new
DBAdapter(getApplicationContext());
try{
dbAdapter.open();
String shop = shopText.getText().toString();
String deal = dealText.getText().toString();
String location = locationText.getText().toString();
String website = websiteText.getText().toString();
String category = categoryText.getText().toString();
}
catch(Exception e){
Log.d("Add Data ", e.getMessage());
}
finally{
if (dbAdapter != null)
dbAdapter.close();
}
}
});
The above kind of syntax always works for me.

calling menu from other activity

please guide me how can i call the menu on the other activity
Like here is the main activity
package com.droidnova.android.howto.optionmenu;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
public class ControlMenu extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.settings:
Intent intent = new Intent(this, ShowSettings.class);
startActivity(intent);
break;
case R.id.services: Toast.makeText(this, "You pressed the text!", Toast.LENGTH_LONG).show();
break;
case R.id.Quit:
new Thread(new Runnable() {
public void run() {
ControlMenu.this.finish();
// The following makes the Android Gods frown upon me
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
}
}).start();
break;
default:
break;
}
return true;
}
}
now i have make another activity in which i need to show the same menu in this
package com.droidnova.android.howto.optionmenu;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class ShowSettings extends Activity {
Prefs myprefs = null;
final String tag = "CH12:ShowSettings";
AlertDialog.Builder adb;// = new AlertDialog.Builder(this);
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.showsettings);
this.myprefs = new Prefs(getApplicationContext());
// load screen
PopulateScreen();
this.adb = new AlertDialog.Builder(this);
final Button savebutton = (Button) findViewById(R.id.settingssave);
// create anonymous click listener to handle the "save"
savebutton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
try {
// get the string and do something with it.
final EditText email = (EditText) findViewById(R.id.emailaddress);
if (email.getText().length() == 0) {
AlertDialog ad = ShowSettings.this.adb.create();
ad.setMessage("Please Enter Your Email Address");
ad.show();
return;
}
final EditText serverurl = (EditText) findViewById(R.id.serverurl);
if (serverurl.getText().length() == 0) {
AlertDialog ad = ShowSettings.this.adb.create();
ad.setMessage("Please Enter The Server URL");
ad.show();
return;
}
// save off values
ShowSettings.this.myprefs.setEmail(email.getText().toString());
ShowSettings.this.myprefs.setServer(serverurl.getText().toString());
ShowSettings.this.myprefs.save();
// we're done!
finish();
} catch (Exception e) {
Log.i(ShowSettings.this.tag, "Failed to Save Settings [" + e.getMessage() + "]");
}
}
});
}
private void PopulateScreen() {
try {
final EditText emailfield = (EditText) findViewById(R.id.emailaddress);
final EditText serverurlfield = (EditText) findViewById(R.id.serverurl);
emailfield.setText(this.myprefs.getEmail());
serverurlfield.setText(this.myprefs.getServer());
} catch (Exception e) {
}
}
}
what should i write in the above code so my menu can also appear over here .
Create the menu as an xml resource, then you can access it from everywhere. Check the documentation. If you need to pass a certain data from only one activity to the other, extending Application seems too much, given you could just pass the info as en extra in the Intent. Besides there are "dangers" in that way of doing things (because of the activity lyfecicle) so you should use SharedPreferences in that case (instead of creating an Application global variable).
If you want to share some information or data or lists (or anything really) with your app, you should look at the following link and make your app as follows:
How to declare global variables in Android?

Categories

Resources