For some reason I keep getting a nullpointer exception with my double parsing. AFter further inquiry there seems to be some issue with my JSON Objects but I have no clue what the issue is.I am pulling JSON data form openweathermap api. I scuessfully pulled and printed the data into the log.i, however when I try to access with the JSONObject I am getting an error. Please help.
Code:
package com.anuraagy.myweather;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import android.content.*;
import android.os.Build;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
public class MyActivity extends Activity {
private String s;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, 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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
private JSONObject myObject,mainObject,nameObject;
private ImageView myImage;
private TextView titleText;
private String hello,weatherName,max_temp,min_temp;
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_my, container, false);
RequestTask task = new RequestTask();
task.execute(new String[]{"http://api.openweathermap.org/data/2.5/weather?q=Ashburn&APPID=970bf0e4978dae293b065f8f2830ba58"});
return rootView;
}
public class RequestTask extends AsyncTask<String, String, String> {
private TextView myView;
private String s;
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else {
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
Log.i("", responseString);
return responseString;
}
#Override
protected void onPostExecute(String result){
Log.i("","hello");
super.onPostExecute(result);
try {
myObject = new JSONObject(result);
nameObject = myObject.getJSONObject("weather");
weatherName = nameObject.getString("main");
mainObject = myObject.getJSONObject("main");
Log.i("Wather Name",weatherName);
Log.i("mainObject",mainObject.toString());
hello = mainObject.getString("temp");
max_temp = mainObject.getString("temp_max");
min_temp = mainObject.getString("temp_min");
} catch(JSONException jsonException){
}
double f = Double.parseDouble(hello);
double max = Double.parseDouble(max_temp);
double min = Double.parseDouble(min_temp);
double realMax = (max - 273)* 1.8 + 32;
double realMin = (min - 273)* 1.8 + 32;
double realTemp = (max - 273)* 1.8 + 32;
int myMax = (int)realMax;
int myMin = (int)realMin;
int myWeather = (int)realTemp;
titleText = (TextView)getActivity().findViewById(R.id.textView3);
String fe = titleText.getText().toString();
fe.replace("definetly",weatherName);
myView = (TextView)getActivity().findViewById(R.id.textView);
// if()
// {
//
// }
// else
// {
//
// }
myImage = (ImageView)getActivity().findViewById(R.id.imageView);
myImage.setImageResource(R.drawable.clearnight);
String weather = myWeather + "";
myView.setText(weather + (char) 0x00B0 +"F");
// //Do anything with response..
}
}
}
}
Error:
10-16 10:01:26.398 664-664/com.anuraagy.myweather E/Trace﹕ error opening trace file: No such file or directory (2)
10-16 10:01:35.058 664-668/com.anuraagy.myweather D/dalvikvm﹕ GC_CONCURRENT freed 75K, 2% free 11112K/11335K, paused 17ms+3ms, total 312ms
10-16 10:01:35.058 664-664/com.anuraagy.myweather D/dalvikvm﹕ WAIT_FOR_CONCURRENT_GC blocked 282ms
10-16 10:01:35.498 664-664/com.anuraagy.myweather D/gralloc_goldfish﹕ Emulator without GPU emulation detected.
10-16 10:01:38.388 664-680/com.anuraagy.myweather I/﹕ {"coord":{"lon":-77.49,"lat":39.04},"sys":{"type":1,"id":2856,"message":0.0194,"country":"US","sunrise":1413458470,"sunset":1413498574},"weather":[{"id":701,"main":"Mist","description":"mist","icon":"50d"},{"id":721,"main":"Haze","description":"haze","icon":"50d"},{"id":741,"main":"Fog","description":"fog","icon":"50d"}],"base":"cmc stations","main":{"temp":288.03,"pressure":1008,"humidity":100,"temp_min":286.15,"temp_max":290.15},"wind":{"speed":2.86,"deg":261.502},"clouds":{"all":90},"dt":1413468071,"id":4744870,"name":"Ashburn","cod":200}
10-16 10:01:38.398 664-664/com.anuraagy.myweather I/﹕ hello
10-16 10:01:38.438 664-664/com.anuraagy.myweather D/AndroidRuntime﹕ Shutting down VM
10-16 10:01:38.438 664-664/com.anuraagy.myweather W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x40a13300)
10-16 10:01:38.448 664-664/com.anuraagy.myweather E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at java.lang.StringToReal.parseDouble(StringToReal.java:244)
at java.lang.Double.parseDouble(Double.java:295)
at com.anuraagy.myweather.MyActivity$PlaceholderFragment$RequestTask.onPostExecute(MyActivity.java:141)
at com.anuraagy.myweather.MyActivity$PlaceholderFragment$RequestTask.onPostExecute(MyActivity.java:91)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Be careful - "weather" is a JSONArray, not a JSONObject. The NullPointerException is likely due to that.
Try instead using myObject.getJSONArray("weather"), and from there iterate through the JSONObjects inside.
See here for more information on that last part: Accessing members of items in a JSONArray with Java
It looks like myObject doesn't have item named "temp", so:
- on line 133 you set hello to null
- on line 141 you pass that null to Double.parseDouble()
- get your exception because class Double can't digest null
That's it!
Check it in the debugger, but I'm almost sure - according to your stack trace
Related
I was making a code to create a show list by ListView{in content_main.xml} like contact view.
I build a database in the (SQLite Expert Professional) with a table(name: "contact") that was contained a few name and family and numbers, with ID,NAME,fAMILY and PHONE NUMBER columns.
ID was unique, auto increment and primary key...other were Text except number that was CHAR.
then I calling them to my ListView as you see in below.(before it I made a row_list activity to made my listview , custom) but there was an Error and I can't find it.
{I could find my database.db file with that's table in the source data files that means my mistake wasn't from creating database.}
plz help me.I wanna learn android (as fast as i can) to get a JOB and I need it..
Errors.Android Monitor.Logcat
09-08 05:27:32.005 5692-5692/? W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x94c4fb20)
09-08 05:27:32.005 5692-5692/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: mizco.phonebook, PID: 5692
java.lang.RuntimeException: Unable to start activity ComponentInfo{mizco.phonebook/mizco.phonebook.Main}: android.database
.CursorIndexOutOfBoundsException: Index 5 requested, with a size of 5
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2193)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5019)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.database.CursorIndexOutOfBoundsException: Index 5 requested, with a size of 5
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:426)
at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
at mizco.phonebook.database.getfulllist(database.java:97)
at mizco.phonebook.Main.onCreate(Main.java:36)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2157)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5019)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Main.java
package mizco.phonebook;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class Main extends AppCompatActivity {
private database db;
private String [][] res ;
private ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
list = (ListView) findViewById(R.id.main_list);
db = new database(this);
db.startusing();
db.open();
res = db.getfulllist();
db.close();
list.setAdapter(new AA());
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
class AA extends ArrayAdapter<String>{
public AA() {
super(Main.this, R.layout.row_list, res[0]);
}
#NonNull
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater in = getLayoutInflater();
View row = in.inflate(R.layout.row_list,parent,false);
TextView name = (TextView) row.findViewById(R.id.row_name);
TextView number = (TextView) row.findViewById(R.id.row_number);
name.setText(res[0][position]+" "+res[1][position]);
number.setText(res[2][position]);
return row;
}
}
}
Class : database.java
package mizco.phonebook;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Created by Mahdi on 9/2/2017.
*/
public class database extends SQLiteOpenHelper {
public static String dbname= "database";
public static String dbpath="";
private Context mctxt;
private SQLiteDatabase mydb;
public database(Context context) {
super(context, dbname, null, 1);
mctxt = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
}
private boolean existdatabase(){
File m312 = new File(dbpath+dbname);
return m312.exists();
}
private void copydatabase(){
try {
InputStream IS = mctxt.getAssets().open(dbname);
OutputStream OS = new FileOutputStream(dbpath+dbname);
byte[] buffer = new byte[1024];
int length;
while ((length = IS.read(buffer))>0){
OS.write(buffer,0,length);
}
OS.flush();
OS.close();
IS.close();
} catch (Exception e) {
}
}
public void open(){
mydb = SQLiteDatabase.openDatabase(dbpath+dbname, null, SQLiteDatabase.OPEN_READWRITE);
}
public void close(){
mydb.close();
}
public void startusing () {
dbpath = mctxt.getFilesDir().getParent() + "/databases/";
if (!existdatabase()) {
this.getWritableDatabase();
copydatabase();
}
}
public String[][] getfulllist(){
Cursor cu = mydb.rawQuery("select * from Contact",null);
String [][] r = new String[3][cu.getCount()];
for (int i= 0;i<=cu.getCount();i++){
cu.moveToPosition(i);
r[0][i]=cu.getString(1);
r[1][i]=cu.getString(2);
r[2][i]=cu.getString(3);
}
return r;
}
}
You're stepping off the end of the cursor. Your code should read
for (int i= 0;i < cu.getCount();i++){
cu.moveToPosition(i);
r[0][i]=cu.getString(1);
r[1][i]=cu.getString(2);
r[2][i]=cu.getString(3);
}
return r;
It is always giving Incorrect credentials, I have double checked the database ,Is there some issue with the code . I am new to android studio,
Any kind of help will be appreciated.
MainActivity
package com.tarun.proxy_maar;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private EditText editTextUserName;
private EditText editTextPassword;
public static final String USER_NAME = "USERNAME";
String username;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextUserName = (EditText) findViewById(R.id.editTextUserName);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
}
public void invokeLogin(View view){
username = editTextUserName.getText().toString();
password = editTextPassword.getText().toString();
login(username,password);
}
private void login(final String username, String password) {
class LoginAsync extends AsyncTask<String, Void, String>{
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(MainActivity.this, "Please wait", "Loading...");
}
#Override
protected String doInBackground(String... params) {
String uname = params[0];
String pass = params[1];
InputStream is = null;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", uname));
nameValuePairs.add(new BasicNameValuePair("password", pass));
String result = null;
try{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(
"http://shaadi.web44.net/hello.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String result){
String s = result.trim();
loadingDialog.dismiss();
if(s.equalsIgnoreCase("success")){
Intent intent = new Intent(MainActivity.this, UserProfile.class);
intent.putExtra(USER_NAME, username);
finish();
startActivity(intent);
}else {
Toast.makeText(getApplicationContext(), "Invalid User Name or Password", Toast.LENGTH_LONG).show();
}
}
}
LoginAsync la = new LoginAsync();
la.execute(username, password);
}
#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);
}
}
PHP SCRIPT ON WEBSERVER
<?php
define('HOST','host');
define('USER','user');
define('PASS','password');
define('DB','database');
$con = mysqli_connect(HOST,USER,PASS,DB);
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "select * from login where username='$username' and password='$password'";
$res = mysqli_query($con,$sql);
$check = mysqli_fetch_array($res);
if(isset($check)){
echo 'success';
}else{
echo 'failure';
}
mysqli_close($con);
?>
Logcat
10-11 07:57:42.852 28481-28481/? I/art﹕ Not late-enabling -Xcheck:jni (already on)
10-11 07:57:42.852 28481-28481/? I/art﹕ Late-enabling JIT
10-11 07:57:42.856 28481-28481/? I/art﹕ JIT created with code_cache_capacity=2MB compile_threshold=1000
10-11 07:57:42.897 28481-28488/? E/art﹕ Failed writing handshake bytes (-1 of 14): Broken pipe
10-11 07:57:42.897 28481-28488/? I/art﹕ Debugger is no longer active
10-11 07:57:42.900 28481-28481/? W/System﹕ ClassLoader referenced unknown path: /data/app/com.tarun.proxy_maar-2/lib/x86
10-11 07:57:43.079 28481-28504/? D/OpenGLRenderer﹕ Use EGL_SWAP_BEHAVIOR_PRESERVED: true
10-11 07:57:43.082 28481-28481/? D/﹕ HostConnection::get() New Host Connection established 0xabe7d170, tid 28481
10-11 07:57:43.135 28481-28504/? D/﹕ HostConnection::get() New Host Connection established 0xabe7d480, tid 28504
10-11 07:57:43.141 28481-28504/? I/OpenGLRenderer﹕ Initialized EGL, version 1.4
10-11 07:57:43.311 28481-28504/? W/EGL_emulation﹕ eglSurfaceAttrib not implemented
10-11 07:57:43.311 28481-28504/? W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xad7918a0, error=EGL_SUCCESS
10-11 07:58:56.273 28481-28504/com.tarun.proxy_maar W/EGL_emulation﹕ eglSurfaceAttrib not implemented
10-11 07:58:56.274 28481-28504/com.tarun.proxy_maar W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xad7bf200, error=EGL_SUCCESS
10-11 07:58:56.939 28481-28504/com.tarun.proxy_maar E/Surface﹕ getSlotFromBufferLocked: unknown buffer: 0xab815a40
10-11 07:58:57.128 28481-28504/com.tarun.proxy_maar W/EGL_emulation﹕ eglSurfaceAttrib not implemented
10-11 07:58:57.128 28481-28504/com.tarun.proxy_maar W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa2e1e6c0, error=EGL_SUCCESS
10-11 07:59:00.474 28481-28504/com.tarun.proxy_maar E/Surface﹕ getSlotFromBufferLocked: unknown buffer: 0xab8159d0
I use the jsoup library to post data from my android apps and it's way easier, where's an example
Document doc = Jsoup.connect("http://shaadi.web44.net/hello.php")
.data("username", uname)
.data("password", pass)
.userAgent("some user agent..or not...")
.timeout(30000)
.post();
String httpresponse = doc.text();
I am new to develop an android application. I have read a lot of related post regarding the question I was asking but the tips or solution from the post did not solve my problem. (Looking for the solution for a week already, really need help in order to proceed with my project) Thanks a lot...
Error line No 121
Image LinK
update.java:
package pounkumarpurushothaman.ghssvmm;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class update extends ActionBarActivity {
public static final String KEY_121 ="http://ghssvmm.site40.net/update.php";
static Activity thisActivity = null;
InputStream is = null;
// LinearLayout yy=(LinearLayout)findViewById(R.id.uy);
// LinearLayout pp=(LinearLayout)findViewById(R.id.up);
//LinearLayout cc=(LinearLayout)findViewById(R.id.uc);
//LinearLayout ca=(LinearLayout)findViewById(R.id.uca);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
getServerData();
}
#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_update, 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 void getServerData() {
thisActivity=this;
EditText f = (EditText) findViewById(R.id.ufst);
EditText l = (EditText) findViewById(R.id.ulst);
Spinner bld=(Spinner)findViewById(R.id.ubld);
Spinner stat=(Spinner)findViewById(R.id.ustatus);
Spinner bth=(Spinner)findViewById(R.id.ubat);
EditText dob = (EditText) findViewById(R.id.udob);
EditText phn1 = (EditText) findViewById(R.id.uphn);
EditText phn2 = (EditText) findViewById(R.id.uphn2);
EditText padd = (EditText) findViewById(R.id.upadd);
EditText radd = (EditText) findViewById(R.id.uradd);
EditText vill = (EditText) findViewById(R.id.uvill);
Spinner sec=(Spinner)findViewById(R.id.usec);
Spinner deg=(Spinner)findViewById(R.id.udeg);
EditText dept = (EditText) findViewById(R.id.udept);
EditText clg = (EditText) findViewById(R.id.uclg);
EditText yop = (EditText) findViewById(R.id.uyop);
EditText pos = (EditText) findViewById(R.id.upos);
EditText cmp = (EditText) findViewById(R.id.ucom);
EditText cadd = (EditText) findViewById(R.id.ucaddr);
String result = "";
//the year data to send
final ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("email","abc#gmail.com"));
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(KEY_121);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Toast.makeText(thisActivity, "Error in http connection " + e.toString(),Toast.LENGTH_LONG).show();
}
}
});
thread.start();
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line+"n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Toast.makeText(this, "Error converting result "+e.toString(),Toast.LENGTH_LONG).show();
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
f.setText(json_data.getString("fname"));
l.setText(json_data.getString("lname"));
dob.setText(json_data.getString("dob"));
switch(json_data.getString("blood")){
case "O Positive":
bld.setSelection(1);
break;
case "O Negative":
bld.setSelection(2);
break;
case "A Positive":
bld.setSelection(3);
break;
case "A Negative":
bld.setSelection(4);
break;
case "B Positive":
bld.setSelection(5);
break;
case "B Negative":
bld.setSelection(6);
break;
case "AB Positive":
bld.setSelection(7);
break;
case "AB Negative":
bld.setSelection(8);
break;
}
switch(json_data.getString("section")) {
case "A":
sec.setSelection(1);
break;
case "B":
sec.setSelection(2);
break;
case "C":
sec.setSelection(3);
break;
}
phn1.setText(json_data.getString("phn"));
phn2.setText(json_data.getString("phn2"));
padd.setText(json_data.getString("add"));
radd.setText(json_data.getString("add2"));
switch(json_data.getString("status")) {
case "Student":
stat.setSelection(1);
/* cc.setVisibility(View.INVISIBLE);
yy.setVisibility(View.INVISIBLE);
pp.setVisibility(View.INVISIBLE);
ca.setVisibility(View.INVISIBLE);*/
break;
case "Employee":
stat.setSelection(2);
/*cc.setVisibility(View.VISIBLE);
yy.setVisibility(View.VISIBLE);
pp.setVisibility(View.VISIBLE);
ca.setVisibility(View.VISIBLE);*/
break;
case "Un Employee":
stat.setSelection(3);
/* cc.setVisibility(View.INVISIBLE);
yy.setVisibility(View.VISIBLE);
pp.setVisibility(View.INVISIBLE);
ca.setVisibility(View.INVISIBLE);*/
break;
}
switch(json_data.getString("degree")) {
case "B.E":
deg.setSelection(1);
break;
case "Arts and Science":
deg.setSelection(2);
break;
case "Medical":
deg.setSelection(3);
break;
}
dept.setText(json_data.getString("dept"));
clg.setText(json_data.getString("clg"));
yop.setText(json_data.getString("yop"));
pos.setText(json_data.getString("pos"));
cmp.setText(json_data.getString("com"));
cadd.setText(json_data.getString("caddr"));
vill.setText(json_data.getString("vill"));
//Get an output to the screen
}
}catch(JSONException e) {
Toast.makeText(this, "Error parsing data " + e.toString(), Toast.LENGTH_LONG).show();
}
}
}
**
Logcat :
**
04-06 14:11:39.580 25919-25919/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: pounkumarpurushothaman.ghssvmm, PID: 25919
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{pounkumarpurushothaman.ghssvmm/pounkumarpurushothaman.ghssvmm.update}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2225)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2388)
at android.app.ActivityThread.access$800(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
at android.app.Activity.findViewById(Activity.java:2081)
at pounkumarpurushothaman.ghssvmm.update.<init>(update.java:34)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1572)
at android.app.Instrumentation.newActivity(Instrumentation.java:1088)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2215)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2388)
at android.app.ActivityThread.access$800(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
.
Here's how you get response after your POST request is executed .
HttpResponse response = httpClient.execute(httpPost);
String op = EntityUtils.toString(response.getEntity(), "UTF-8");
Log.d("Response:", op);
I am trying to show images in grid-view using tab-swipe. But when include async-task to fetch images from json URL the app does not even starting. It just crashes and closed. Here is my code.
import android.support.v4.app.Fragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.GridView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class GamesFragment extends Fragment {
public GamesFragment(){}
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
GridView gridview;
GridViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
ArrayList<HashMap<String, String>> items;
private Button button;
static String CATEGORY = "category";
int setlimit = 6;
int tolimit = 5;
static String IMAGE = "image";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.gridview_main, container, false);
new DownloadJSON().execute();
return rootView;
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(getActivity());
// Set progressdialog title
mProgressDialog.setTitle("Student Government App");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL
("http://jsonurl.com");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("wallpaper");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("category", jsonobject.getString("category"));
map.put("image", jsonobject.getString("image"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
gridview = (GridView) getView().findViewById(R.id.gridViewCustom);
// Pass the results into ListViewAdapter.java
adapter = new GridViewAdapter(getActivity(), arraylist);
gridview.setAdapter(adapter);
mProgressDialog.dismiss();
}
}
}
How can i prevent it from app crash? Any help would be be great.
Logcat:
07-03 15:22:36.692 838-838/info.androidhive.tabsswipe D/ActivityThread﹕ ACT- AM_ON_PAUSE_CALLED ActivityRecord{41353570 token=android.os.BinderProxy#41352cb0 {info.androidhive.tabsswipe/info.androidhive.tabsswipe.MainActivity}}
07-03 15:22:36.707 838-838/info.androidhive.tabsswipe D/ActivityThread﹕ ACT-PAUSE_ACTIVITY_FINISHING handled : 0 / android.os.BinderProxy#41352cb0
07-03 15:22:36.904 838-838/info.androidhive.tabsswipe D/OpenGLRenderer﹕ Flushing caches (mode 0)
07-03 15:22:36.944 838-838/info.androidhive.tabsswipe D/OpenGLRenderer﹕ Flushing caches (mode 0)
07-03 15:22:36.989 838-838/info.androidhive.tabsswipe D/OpenGLRenderer﹕ Flushing caches (mode 0)
07-03 15:22:37.003 838-838/info.androidhive.tabsswipe E/WindowManager﹕ Activity info.androidhive.tabsswipe.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#4136f300 that was originally added here
android.view.WindowLeaked: Activity info.androidhive.tabsswipe.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#4136f300 that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:418)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:294)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:226)
at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:151)
at android.view.Window$LocalWindowManager.addView(Window.java:547)
at android.app.Dialog.show(Dialog.java:277)
at info.androidhive.tabsswipe.GamesFragment$DownloadJSON.onPreExecute(GamesFragment.java:65)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at info.androidhive.tabsswipe.GamesFragment.onCreateView(GamesFragment.java:48)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1500)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:938)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1115)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1478)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:478)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1068)
at android.support.v4.view.ViewPager.populate(ViewPager.java:914)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1436)
at android.view.View.measure(View.java:15264)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4918)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:15264)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:833)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
at android.view.View.measure(View.java:15264)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4918)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2161)
at android.view.View.measure(View.java:15264)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2131)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1242)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1435)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1127)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4609)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:747)
at android.view.Choreographer.doCallbacks(Choreographer.java:567)
at android.view.Choreographer.doFrame(Choreographer.java:536)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:733)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:153)
at android.app.ActivityThread.main(ActivityThread.java:4987)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:821)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
at dalvik.system.NativeStart.main(Native Method)
07-03 15:22:37.004 838-838/info.androidhive.tabsswipe D/OpenGLRenderer﹕ Flushing caches (mode 0)
07-03 15:22:37.004 838-838/info.androidhive.tabsswipe D/ActivityThread﹕ ACT-DESTROY_ACTIVITY handled : 1 / android.os.BinderProxy#41352cb0
07-03 15:22:37.004 838-838/info.androidhive.tabsswipe D/OpenGLRenderer﹕ Flushing caches (mode 1)
You should move gridview initialized in your onCreateView(...) before new DownloadJSON().execute();
gridview = (GridView) rootview.findViewById(R.id.gridViewCustom);
Change you oncreateview like this
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.gridview_main, container, false);
gridview = (GridView) rootView.findViewById(R.id.gridViewCustom);
new DownloadJSON().execute();
return rootView;
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
ProgressDialog progressDialog = null;
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Loading , Please wait...");
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
super.onPreExecute();
}
change your onPostExecute this way
#Override
protected void onPostExecute(Void args) {
mProgressDialog.dismiss();
gridview = (GridView) getView().findViewById(R.id.gridViewCustom);
// Pass the results into ListViewAdapter.java
adapter = new GridViewAdapter(getActivity(), arraylist);
gridview.setAdapter(adapter);
super.onPostExecute(arg);
}
}
You open That app in Debugging mode
and see the error in console (choose warning) and find the error and clear it
i am the newbee in Android Development.
I had developed an app contains a login, the credentials must be passed in the text field and later it will call a webservice.
I am facing the issue as user and password is not getting copied at the required position.
Please help me out.
package com.authorwjf.http_get;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import android.app.Activity;
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 Main extends Activity implements OnClickListener {
EditText txtUserName;
EditText txtPassword;
#Override
public void onCreate(Bundle savedInstanceState) {
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(false);
new LongRunningGetIO().execute();
}
private class LongRunningGetIO extends AsyncTask <Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n>0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n>0) out.append(new String(b, 0, n));
}
return out.toString();
}
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
String user= txtUserName.getText().toString();
String pass= txtPassword.getText().toString();
System.out.println("USERRRR"+user);
System.out.println(pass);
//String user="at#ril.com";
//String pass= "123456";
String accessTokenQry = "{"+
"\"uid\":\""+user+"\","+
"\"password\":\""+pass+"\","+
"\"consumptionDeviceId\":\"fder-et3w-3adw2-2erf\","+
"\"consumptionDeviceName\":\"Samsung Tab\""+
"}";
HttpPost httpPost = new HttpPost("http://devssg01.ril.com:8080/v2/dip/auth/login");
httpPost.setHeader("Content-Type",
"application/json");
httpPost.setHeader("X-API-Key",
"l7xx7914b8704b2d4b029ab9c4b1b9c66dbf");
StringEntity input;
try {
input = new StringEntity(accessTokenQry);
httpPost.setEntity(input);
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String text = null;
try {
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
}
protected void onPostExecute(String results) {
if (results!=null) {
EditText et = (EditText)findViewById(R.id.my_edit);
et.setText(results);
}
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(true);
}
}
}
The LogCat Output is:
08-10 01:20:23.977: W/dalvikvm(760): threadid=14: thread exiting with uncaught exception (group=0x414c4700)
08-10 01:20:23.984: E/AndroidRuntime(760): FATAL EXCEPTION: AsyncTask #4
08-10 01:20:23.984: E/AndroidRuntime(760): java.lang.RuntimeException: An error occured while executing doInBackground()
08-10 01:20:23.984: E/AndroidRuntime(760): at android.os.AsyncTask$3.done(AsyncTask.java:299)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.lang.Thread.run(Thread.java:841)
08-10 01:20:23.984: E/AndroidRuntime(760): Caused by: java.lang.NullPointerException
08-10 01:20:23.984: E/AndroidRuntime(760): at com.authorwjf.http_get.Main$LongRunningGetIO.doInBackground(Main.java:66)
08-10 01:20:23.984: E/AndroidRuntime(760): at com.authorwjf.http_get.Main$LongRunningGetIO.doInBackground(Main.java:1)
08-10 01:20:23.984: E/AndroidRuntime(760): at android.os.AsyncTask$2.call(AsyncTask.java:287)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
08-10 01:20:23.984: E/AndroidRuntime(760): ... 3 more
You are trying to initialize EditTexts before layout loaded.
If you want to get EditText on layout, you must initialize it after layout loaded.
Here is correct code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
}
use this
EditText textw3d =(EditText) findViewById(R.id.editText3d);
final String strd3d = textw3d.getText().toString();
I suggest following change in your code.
Just write following lines
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
above
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
Move the lines where you get the reference to text views after the setContentView function call:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
}
The fact is you need to call setContentView before initializing any widget in your layout because this is the call that "loads" your layout defined in layout_main.xml file into your activity.
Thanks a lot Guyz,
The issue is resolved now.
Special appreciation to JustWork
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
}