setOnClickListener and findByViewId - android

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.

Related

I'm Not able to assign ArrayList returned by OnPostExecute method of AysncTask in main activity

I'm trying to return an ArrayList from onPostExecute method of AsyncTask in Main Activity. I'm assigning returned ArrayList to the searchedText ArrayList of main activity. I'm not able to get elements of searchedText ArrayList in btnSearch onClickListener. Please let me know what is wrong in the code.
package com.example.dharak029.hw3_group09;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.io.InputStream;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
EditText textIn;
ImageButton buttonAdd;
LinearLayout container;
ArrayList<String> wordList;
byte[] buffer;
String text;
ArrayList<String> searchText;
ArrayList<String> searchedText;
int keywordCount=0;
void setResult(ArrayList<String> searchedText){
this.searchedText = searchedText;
Log.d("result",""+searchedText.size());
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textIn = (EditText)findViewById(R.id.textin);
buttonAdd = (ImageButton)findViewById(R.id.add);
container = (LinearLayout)findViewById(R.id.container);
wordList = new ArrayList<String>();
searchText = new ArrayList<String>();
try {
InputStream is = getAssets().open("textfile.txt");
int size = is.available();
buffer = new byte[size];
is.read(buffer);
is.close();
text = new String(buffer);
int startIndex = 0;
for(int i=0;i<text.length()/30;i++){
searchText.add(text.substring(startIndex,startIndex+30));
startIndex = startIndex+30;
}
}
catch (Exception e){
}
findViewById(R.id.btnSearch).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(String word: wordList){
new DoWork(MainActivity.this).execute(word);
}
Intent intent = new Intent(MainActivity.this,WordsFound.class);
intent.putExtra("searchResults",searchedText);
startActivity(intent);
}
});
buttonAdd.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if (keywordCount <= 20) {
LayoutInflater layoutInflater =
(LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View addView = layoutInflater.inflate(R.layout.row, null);
final TextView textOut = (TextView) addView.findViewById(R.id.textout);
textOut.setText(textIn.getText().toString());
wordList.add(textIn.getText().toString());
ImageButton buttonRemove = (ImageButton) addView.findViewById(R.id.remove);
final View.OnClickListener thisListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
((LinearLayout) addView.getParent()).removeView(addView);
wordList.remove(textOut.getText().toString());
listAllAddView();
keywordCount--;
}
};
buttonRemove.setOnClickListener(thisListener);
container.addView(addView);
listAllAddView();
keywordCount++;
}
}
});
}
private void listAllAddView(){
int childCount = container.getChildCount();
for(int i=0; i<childCount; i++){
View thisChild = container.getChildAt(i);
}
}
class DoWork extends AsyncTask<String,Integer,ArrayList<String>>{
ArrayList<String> searchResult = new ArrayList<String>();
ProgressBar progress;
MainActivity activity;
public DoWork(MainActivity activity) {
this.activity = activity;
}
#Override
protected ArrayList<String> doInBackground(String... params) {
for(int i=0;i<searchText.size();i++){
String text = searchText.get(i);
if(text.contains(params[0]))
searchResult.add(text);
}
Log.d("demo",""+searchResult.size());
return searchResult;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(ArrayList<String> aVoid) {
super.onPostExecute(aVoid);
activity.setResult(aVoid);
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
}
}
You can't put ArrayList in extras by putExtra() you have to use putStringArrayListExtra(). Try below code.
Intent intent = new Intent(MainActivity.this,WordsFound.class);
intent.putStringArrayListExtra("searchResults",searchedText);
startActivity(intent);
The problem is in the following code:
findViewById(R.id.btnSearch).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(String word: wordList){
new DoWork(MainActivity.this).execute(word);
}
Intent intent = new Intent(MainActivity.this, WordsFound.class);
intent.putExtra("searchResults",searchedText);
startActivity(intent);
}
});
Let's dissect the code. No problem with the following code. It's the usual code for click listener:
findViewById(R.id.btnSearch).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
...
}
Now, we look into the body code, from the following code:
for(String word: wordList){
new DoWork(MainActivity.this).execute(word);
}
We knew that DoWork is an AsyncTask which is doing an asynchronous process. So, the next code will be executed eventhough the DoWork haven't finished its process.
Let's see the next code:
Intent intent = new Intent(MainActivity.this, WordsFound.class);
intent.putExtra("searchResults", searchedText);
startActivity(intent);
Here you put the extra from searchedText variable which is only initialized in onCreate with:
searchText = new ArrayList<String>();
So, you'll always have the empty list when setting the extra.
To overcome the empty list issue, you need to send the extra only after the DoWork is finished doing its job. You can try calling the Intent inside the setResult

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

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) {

Eclipse says onClickListener variable in Android cannot be resolved, but has been created?

In my project i several onClick listeners, and all of them are fine, but one, i can not find and error in the code, if i delete the code and retype it and save it, it is fine without errors, if i close and eclipse and comeback later, variable cant be resolved again.
This is where it cant be resolved in the code:
Button webButton = (Button) newStockRow.findViewById(R.id.webButton);
webButton.setOnClickListener(getStockFromWebClickListener);
and this is how i create it:
public OnClickListener getStockFromWebClickListener = new OnClickListener(){
#Override
public void onClick(View arg0) {
TableRow tableR = (TableRow) arg0.getParent();
TextView stock = (TextView) tableR.findViewById(R.id.stockSymbolTextView);
String stockSymbol = stock.getText().toString();
String stockURL = getString(R.string.yahoo_stock_url) + stockSymbol;
Intent getStockWebPage = new Intent(Intent.ACTION_VIEW, Uri.parse(stockURL));
startActivity(getStockWebPage);
}
};
Code for full File:
package com.gscore.quotestock;
import java.util.Arrays;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
public class StockQ extends Activity {
public final static String STOCK_SYMBOL = "com.gscore.quotestock.STOCK";
private SharedPreferences stockSymbolsEntered;
private TableLayout stockTableScrollView;
private EditText stockSymbolET;
Button enterStockSymbolButton;
Button deleteStocksButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stock_q);
// Get user stock list
stockSymbolsEntered = getSharedPreferences("stockList", MODE_PRIVATE);
// Initialize UI components
stockTableScrollView = (TableLayout) findViewById(R.id.stockTableLayout);
stockSymbolET = (EditText) findViewById(R.id.stockSymbolEditText);
enterStockSymbolButton= (Button) findViewById(R.id.enterButton);
deleteStocksButton= (Button) findViewById(R.id.deleteAllButton);
// Set ClickListeners
enterStockSymbolButton.setOnClickListener(enterButtonClickListener);
deleteStocksButton.setOnClickListener(deleteButtonClickListener);
updateSavedStockList(null);
}
private void updateSavedStockList(String newStockSymbol){
String[] stocks = stockSymbolsEntered.getAll().keySet().toArray(new String[0]);
Arrays.sort(stocks, String.CASE_INSENSITIVE_ORDER);
if (newStockSymbol != null){
insertStockInStockTable(newStockSymbol, Arrays.binarySearch(stocks, newStockSymbol));
} else {
for(int i = 0; i < stocks.length; i++){
insertStockInStockTable(stocks[i], i);
}
}
}
private void saveStockSymbol(String newStock){
String isTheStockNew = stockSymbolsEntered.getString(newStock, null);
SharedPreferences.Editor preferencesEditor = stockSymbolsEntered.edit();
preferencesEditor.putString(newStock, newStock);
preferencesEditor.commit();
if(isTheStockNew == null){
updateSavedStockList(newStock);
}
}
private void insertStockInStockTable(String stock, int arrayIndex){
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View newStockRow = inflater.inflate(R.layout.stock_quote_row, null);
TextView newStockTextView = (TextView) newStockRow.findViewById(R.id.stockSymbolTextView);
newStockTextView.setText(stock);
Button stockQuoteButton = (Button) newStockRow.findViewById(R.id.stockQuoteButton);
stockQuoteButton.setOnClickListener(getStockActivityListener);
Button webButton = (Button) newStockRow.findViewById(R.id.webButton);
webButton.setOnClickListener(getStockFromWebClickListener);
stockTableScrollView.addView(newStockRow, arrayIndex);
}
public OnClickListener enterButtonClickListener= new OnClickListener(){
#Override
public void onClick(View v) {
if(stockSymbolET.getText().length() > 0){
saveStockSymbol(stockSymbolET.getText().toString());
stockSymbolET.setText("");
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(stockSymbolET.getWindowToken(), 0);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(StockQ.this);
builder.setTitle(R.string.invalid_stock_symbol);
builder.setPositiveButton(R.string.ok, null);
builder.setMessage(R.string.missing_stock_symbol);
AlertDialog theAlertDialog = builder.create();
theAlertDialog.show();
}
}
};
private void deleteAllStocks(){
stockTableScrollView.removeAllViews();
}
public OnClickListener deleteButtonClickListener = new OnClickListener(){
#Override
public void onClick(View v) {
deleteAllStocks();
SharedPreferences.Editor preferencesEditor = stockSymbolsEntered.edit();
preferencesEditor.clear();
preferencesEditor.commit();
}
};
public OnClickListener getStockActivityListener = new OnClickListener(){
#Override
public void onClick(View v) {
TableRow tableR = (TableRow) v.getParent();
TextView stock = (TextView) tableR.findViewById(R.id.stockSymbolTextView);
String stockSymbol = stock.getText().toString();
Intent intent = new Intent(StockQ.this, StockInfoActivity.class);
intent.putExtra(STOCK_SYMBOL, stockSymbol);
startActivity(intent);
}
};
public OnClickListener getStockFromWebClickListener = new OnClickListener(){
#Override
public void onClick(View arg0) {
TableRow tableR = (TableRow) arg0.getParent();
TextView stock = (TextView) tableR.findViewById(R.id.stockSymbolTextView);
String stockSymbol = stock.getText().toString();
String stockURL = getString(R.string.yahoo_stock_url) + stockSymbol;
Intent getStockWebPage = new Intent(Intent.ACTION_VIEW, Uri.parse(stockURL));
startActivity(getStockWebPage);
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.stock_q, menu);
return true;
}
}
That's indeed an annoying problem with importing an inner class (or interface) on Eclipse.
What you have to do is instead of:
new OnClickListener()
Write:
new View.OnClickListener()
And make sure that android.view.View is imported.

Android create intent to start activity

I have an app, which consists of a tabhost. I am using a AsyncTask to perform some internet work in the background. Now in the onPostExecute, I want it to start a new activity. When I create a new intent, the new activity is shown, but there are no tabs.. it's just the activity.
Now i've read online how to do this, And i've managed to get into the right direction i think. This is the entire code:
package com.appsoweb.kvodeventer;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ActivityGroup;
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.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class KVOMeldingen extends ActivityGroup {
public static final JSONObject jsonResult = null;
Button bLogin, bCreateAccount, bResetPassword;
EditText etUsername, etPassword;
static String Username;
static String Password;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.meldingen);
final EditText etUsername = (EditText) findViewById(R.id.etUsername);
final EditText etPassword = (EditText) findViewById(R.id.etPassword);
Button bLogin = (Button) findViewById(R.id.bLogin);
Button bCreateAccount = (Button) findViewById(R.id.bCreateAccount);
Button bResetPassword = (Button) findViewById(R.id.bResetPassword);
bLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (etUsername.length() <= 0) {
etUsername.setError("Veld mag niet leeg zijn");
} else if (etPassword.length() <= 0) {
etPassword.setError("Veld mag niet leeg zijn");
} else {
Username = etUsername.getText().toString();
Password = etPassword.getText().toString();
}
LoginTask NDLT = new LoginTask();
NDLT.execute();
}
});
bCreateAccount.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Doe iets hier.......
}
});
bResetPassword.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Doe iets hier........
}
});
}
public static String getUsername() {
return Username;
}
public static String getPassword() {
return Password;
}
class LoginTask extends AsyncTask<Void, Void, JSONObject> {
ProgressDialog waitingDialog;
#Override
protected void onPreExecute() {
waitingDialog = new ProgressDialog(KVOMeldingen.this);
waitingDialog.setMessage("Laden...");
waitingDialog.show();
super.onPreExecute();
}
#Override
protected JSONObject doInBackground(Void... params) {
JSONObject json = JsonFunctionLogin
.getJsonLoginResult("http://api.crossalertdeventer.nl/login.json");
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
super.onPostExecute(json);
if (waitingDialog.isShowing()) {
waitingDialog.dismiss();
Log.d("iets gebeurt", "gedaan");
}
try {
String LoginResult = json.getString("login");
String UserIdResult = json.getString("user_id");
Log.d("LoginResult", LoginResult);
Log.d("LoginUserId", UserIdResult);
json = null;
Intent intent = new Intent(KVOMeldingen.this, KVOCards.class);
View view = getLocalActivityManager().startActivity("KVOCards", intent
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();
replaceView(view);
} catch (Exception e) {
Log.e("KVOMeldingen", "error" + e.getMessage());
}
}
public void replaceView(View v){
setContentView(v);
}
}
}
As you can see: I've created a View that will be shown trough an Intent. But the intent doesn't launch after the onbackground. It gives me an error:
Unable to start Activity componentInfo Unable to add window ... Token..... is not valid... Is your application running?
What am i doing wrong?
Thnx in advance
Starting a new Activity means you are navigating from your TabActivity to a normal Activity. Obviously you can't find a tab in Activity. You have to replace views instead of creating Activities.
Here is a good example of how to use ActivityGroup with TabActivity.
http://web.archive.org/web/20100816175634/http://blog.henriklarsentoft.com/2010/07/android-tabactivity-nested-activities/
But still this approach has been deprecated. You might have to consider using fragments though.
Take a look here, http://developer.android.com/resources/samples/Support4Demos/src/com/example/android/supportv4/app/FragmentTabs.html

Null pointer exception error : database in android

package com.andrd.gps;
import com.android.util.Utils;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
public class EditUserDetailActivity extends Activity{
String strTruckType, strTruckPermit, strEmploymentType;
EditText driverNameEdtxt,ageEdtxt,addressEdtxt,liecenceNoEdtxt,contactNoEdtxt,truckNoEdtxt,fromLocationEdtxt,toLocationEdtxt,longitudeEdtxt,latitudeEdtxt;
LinearLayout addUserLayout, updateUserLayout;
Button updateBtn,cancelBtn;
UserDetail user;
TransportData database;
String strTruckNo;
Spinner employmentTypeSpn, truckPermitSpn, truckTypeSpn;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.add_user);
user=new UserDetail();
database=new TransportData(this);
addUserLayout = (LinearLayout) findViewById(R.id.addUserlayout);
addUserLayout.setVisibility(View.GONE);
driverNameEdtxt = (EditText) findViewById(R.id.driverNameedtx);
ageEdtxt = (EditText) findViewById(R.id.ageEdtxt);
addressEdtxt = (EditText) findViewById(R.id.addressEdtxt);
liecenceNoEdtxt = (EditText) findViewById(R.id.licenceNoEdtxt);
contactNoEdtxt = (EditText) findViewById(R.id.contactNoEdtxt);
truckNoEdtxt = (EditText) findViewById(R.id.truckNoEdtxt);
fromLocationEdtxt = (EditText) findViewById(R.id.fromLocationEdtxt);
toLocationEdtxt = (EditText) findViewById(R.id.toLocationEdtxt);
longitudeEdtxt = (EditText) findViewById(R.id.longitudeEdtxt);
latitudeEdtxt = (EditText) findViewById(R.id.latitudeEdtxt);
Spinner employmentType = (Spinner) findViewById(R.id.DriverSpnr);
employmentType.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item,Utils.driver_type));
Spinner truckType = (Spinner)findViewById(R.id.TruckTypespnr);
truckType.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item,Utils.truck_type));
Spinner truckPermit = (Spinner) findViewById(R.id.TruckPermitSpnr);
truckPermit.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item,Utils.truck_permit));
truckPermit.setSelection(0);
truckPermit.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> adapterView, View view,
int position, long arg3) {
strTruckPermit = adapterView.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
getUserData();
updateBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
boolean ok = false;
try {
user.driverName = driverNameEdtxt.getText().toString();
user.age = ageEdtxt.getText().toString();
user.liecenceNo = liecenceNoEdtxt.getText().toString();
user.address = addressEdtxt.getText().toString();
user.contactNo = contactNoEdtxt.getText().toString();
user.driverType = strEmploymentType;
user.truckNo = truckNoEdtxt.getText().toString();
user.truckPermit = strTruckPermit;
user.truckType = strTruckType;
user.fromLocation= fromLocationEdtxt.getText().toString();
user.toLocation = toLocationEdtxt.getText().toString();
user.latitude = latitudeEdtxt.getText().toString();
user.longitude = longitudeEdtxt.getText().toString();
int n = database.updateUser(user);
if(n>0)
{
ok = true;
}
} catch (Exception e) {
ok= false;
}
finally{
if(ok)
{
Toast.makeText(getApplicationContext(), "Successful update data", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(), "database Error", Toast.LENGTH_LONG).show();
}
}
}
});
cancelBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
finish();
}
});
}
private void getUserData() {
user.truckNo = strTruckNo;
try {
database.getUserDetail(user);
driverNameEdtxt.setText(user.driverName);
ageEdtxt.setText(user.age);
addressEdtxt.setText(user.address);
liecenceNoEdtxt.setText(user.liecenceNo);
contactNoEdtxt.setText(user.contactNo);
employmentTypeSpn.setTag(user.driverType);
truckNoEdtxt.setText(user.truckNo);
truckTypeSpn.setTag(user.truckType);
truckPermitSpn.setTag(user.truckPermit);
fromLocationEdtxt.setText(user.fromLocation);
toLocationEdtxt.setText(user.toLocation);
}
catch (Exception e) {
Toast.makeText(getApplicationContext(), "database Error", Toast.LENGTH_LONG).show();
}
}
}
//error in line no 83(error name null pointer exception)
You aren't setting your Spinner instance variables. You are assigning your spinners to local variables instead.
Instead of:
Spinner employmentType = (Spinner) findViewById(R.id.DriverSpnr);
Spinner truckType = (Spinner)findViewById(R.id.TruckTypespnr);
Spinner truckPermit = (Spinner) findViewById(R.id.TruckPermitSpnr);
you need:
employmentTypeSpn = (Spinner) findViewById(R.id.DriverSpnr);
truckTypeSpn = ...
truckPermitSpn = ...
You need to also get your updateBtn somehow:
updateBtn = (Button) findViewById(R.id.update_button);

Categories

Resources