User Authentication using AsyncTask - android

I'm trying to create simple login form. Following URL returns "true" if the user credentials are validated and "false" otherwise. Simple string is returned.
http:/........../login.php?user=rashid&pass=rashid
The program crashes when I press login button. This is being shown on LogCat:-
FATAL EXCEPTION: main - java.lang.NullPointerException at
com.example.logintry.MainActivity$VerifyLogin.onPostExecution
Here's activit_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="10dp"
>
<EditText
android:id="#+id/etUser"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="User Name"
android:text="rashid"
android:ems="10" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/etPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Password"
android:text="rashid123"
android:inputType="textPassword" />
<Button
android:id="#+id/bLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Login" />
</LinearLayout>
Here's MainActivity.java
For security reasons I've not added actual IP.
package com.example.logintry;
import java.io.IOException;
import java.net.URL;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity implements View.OnClickListener {
private EditText etUser, etPassword;
private Button bLogin;
private String u, p;
private final String KEY_LOGIN_URL = "http://.............../login.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etUser = (EditText) findViewById(R.id.etUser);
etPassword = (EditText) findViewById(R.id.etPassword);
bLogin = (Button) findViewById(R.id.bLogin);
bLogin.setOnClickListener(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);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
u = etUser.getText().toString();
p = etPassword.getText().toString();
VerifyLogin runner = new VerifyLogin();
runner.execute();
}
private class VerifyLogin extends AsyncTask<URL, Void, Void> {
String msg = "";
HttpClient httpClient;
HttpGet httpGet;
HttpResponse response;
HttpEntity entity;
#Override
protected Void doInBackground(URL... urls) {
// TODO Auto-generated method stub
try {
httpClient = new DefaultHttpClient();
httpGet = new HttpGet(KEY_LOGIN_URL + "?user=" + u + "&pass=" + p);
response = httpClient.execute(httpGet);
entity = response.getEntity();
msg = EntityUtils.toString(entity);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (result.equals("true")) {
Toast.makeText(getApplicationContext(), "Valid password",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Invalid Password",
Toast.LENGTH_LONG).show();
}
}
}
}

result is of type Void, which is always null, so result.equals("true") will throw the NPE.
You need to change your VerifyLogin class to extends AsyncTask<URL, Void, String>, and make doInBackground return "true" or "false" as your postExecution method is expecting.

Related

OnClick() is not working for currency converter.

I want to add currency converter in side menu of my app. But i am unable to get conversion after on click().
On click "calculate" i am not getting conversion.
Please see the code why i am not able to click . I have used yahoo api.
CurrencyConverter.java
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import info.androidhive.customlistviewvolley.R;
public class CurrencyConverter extends Fragment {
public CurrencyConverter() {
}
TextView t;
public int to;
public int from;
public String[] val;
public String s;
public Handler handler;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.currency_converter, container, false);
t= (TextView) rootView.findViewById(R.id.textView4);
Spinner s1 = (Spinner) rootView.findViewById(R.id.spinner1);
Spinner s2 = (Spinner) rootView.findViewById(R.id.spinner2);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this.getActivity(), R.array.name, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
val = getResources().getStringArray(R.array.value);
s1.setAdapter(adapter);
s2.setAdapter(adapter);
s1.setOnItemSelectedListener(new spinOne(1));
s2.setOnItemSelectedListener(new spinOne(2));
Button b = (Button) rootView.findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View rootView) {
//t.setText(exResult);
if (from == to) {
Toast.makeText(getActivity().getApplicationContext(), "Invalid", 4000).show();
} else {
try {
// s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22"+val[from]+val[to]+"%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
JSONObject jObj;
jObj = new JSONObject(s);
String exResult = jObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
t.setText(exResult);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
return rootView;
}
public class calculate extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... args) {
try {
s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22"+val[from]+val[to]+"%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
JSONObject jObj;
jObj = new JSONObject(s);
String exResult = jObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
// t.setText(exResult);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return s;
}
#Override
protected void onPostExecute(String exResult) {
// t = (TextView) rootView.findViewById(R.id.textView4);
// t.setText(exResult);
}
}
public String getJson(String url)throws ClientProtocolException, IOException {
StringBuilder build = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String con;
while ((con = reader.readLine()) != null) {
build.append(con);
}
return build.toString();
}
public class spinOne implements AdapterView.OnItemSelectedListener
{
int ide;
spinOne(int i)
{
ide =i;
}
public void onItemSelected(AdapterView<?> parent, View view,
int index, long id) {
if(ide == 1)
from = index;
else if(ide == 2)
to = index;
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
}
CurrencyConverter.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFFFFF"
>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#FFFFFF">
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/one"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/in"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Spinner
android:id="#+id/spinner2"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/equal"
android:textAppearance="?android:attr/textAppearanceLarge" />
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="match_parent"
android:layout_height="122dp"
android:gravity="center"
android:background="#ffffff">
<RelativeLayout
android:id="#+id/relativeLayout2"
android:layout_width="match_parent"
android:layout_height="120dp"
android:gravity="center"
android:background="#ffffff">
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="#string/result"
android:textSize="35dp"
/>
</RelativeLayout>
</RelativeLayout>
<Button
android:id="#+id/button1"
android:layout_marginTop="10dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/calculate" />
</LinearLayout>
</ScrollView>
Error:
05-09 17:33:30.425 2238-2238/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: info.androidhive.customlistviewvolley, PID: 2238
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
at org.json.JSONTokener.nextValue(JSONTokener.java:94)
at org.json.JSONObject.<init>(JSONObject.java:156)
at org.json.JSONObject.<init>(JSONObject.java:173)
at info.androidhive.customlistviewvolley.model.CurrencyConverter$1.onClick(CurrencyConverter.java:74)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
05-09 17:33:30.430 1233-1513/? W/ActivityManager: Force finishing activity info.androidhive.customlistviewvolley/.MainActivity
You are trying to invoke String from UI thread that has no connection to it. As one of the possible workarounds you can create global variable and assign to it at
#Override
protected void onPostExecute(String exResult) {
// t = (TextView) rootView.findViewById(R.id.textView4);
// t.setText(exResult);
globalString = exResult;
}
Afterwards you can use it code. Please read about AsyncTask lifecycle and Android Threads.
updated Answer:
CurreencyConverter.java
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import info.androidhive.customlistviewvolley.R;
public class CurrencyConverter extends Fragment {
public CurrencyConverter() {
}
TextView t;
public int to;
public int from;
public String[] val;
public String s;
String exResult;
public Handler handler;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.currency_converter, container, false);
t= (TextView) rootView.findViewById(R.id.textView4);
Spinner s1 = (Spinner) rootView.findViewById(R.id.spinner1);
Spinner s2 = (Spinner) rootView.findViewById(R.id.spinner2);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this.getActivity(), R.array.name, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
val = getResources().getStringArray(R.array.value);
s1.setAdapter(adapter);
s2.setAdapter(adapter);
s1.setOnItemSelectedListener(new spinOne(1));
s2.setOnItemSelectedListener(new spinOne(2));
Button b = (Button) rootView.findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View View) {
if (from == to) {
Toast.makeText(getActivity().getApplicationContext(), "Invalid", 4000).show();
} else {
new calculate().execute();
}
}
});
return rootView;
}
public class calculate extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... args) {
try {
s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22"+val[from]+val[to]+"%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
JSONObject jObj;
jObj = new JSONObject(s);
exResult = jObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return exResult;
}
#Override
protected void onPostExecute(String exResult) {
t.setText(exResult);
}
}
public String getJson(String url)throws IOException {
StringBuilder build = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String con;
while ((con = reader.readLine()) != null) {
build.append(con);
}
return build.toString();
}
public class spinOne implements AdapterView.OnItemSelectedListener
{
int ide;
spinOne(int i)
{
ide =i;
}
public void onItemSelected(AdapterView<?> parent, View view,
int index, long id) {
if(ide == 1)
from = index;
else if(ide == 2)
to = index;
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
}

Facing Error in GetJson() & OnClick() in Fragments. Plese see code help me for same

I am adding side menu screen content as a Currencyconverter. When i am clicking to calculate currency it is not getting & App is crashing. I have used yahoo API for currency converter.
Facing Error in GetJson() & onClick() in Fragments. Please see code help me for same . i am stuck why this is happening ?
In 1st image is you can see the side menu & 2nd image come after clicking currency converter (via side menu click).
Currencyconverter.java
import android.app.Fragment;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import info.androidhive.customlistviewvolley.R;
public class CurrencyConverter extends Fragment {
public CurrencyConverter() {
}
public int to;
public int from;
public String[] val;
public String s;
public Handler handler;
/**
* Called when the activity is first created.
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.currency_converter, container, false);
/* public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);*/
Spinner s1 = (Spinner) rootView.findViewById(R.id.spinner1);
Spinner s2 = (Spinner) rootView.findViewById(R.id.spinner2);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this.getActivity(), R.array.name, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
val = getResources().getStringArray(R.array.value);
s1.setAdapter(adapter);
s2.setAdapter(adapter);
s1.setOnItemSelectedListener(new spinOne(1));
s2.setOnItemSelectedListener(new spinOne(2));
Button b = (Button) rootView.findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View View) {
TextView t = (TextView) View.findViewById(R.id.textView4);
if (from == to) {
Toast.makeText(getActivity().getApplicationContext(), "Invalid", 4000).show();
} else {
try {
s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22"+val[from]+val[to]+"%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
JSONObject jObj;
jObj = new JSONObject(s);
String exResult = jObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
t.setText(exResult);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public String getJson(String url)throws ClientProtocolException, IOException {
StringBuilder build = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String con;
while ((con = reader.readLine()) != null) {
build.append(con);
}
return build.toString();
}
});
return rootView;
}
public class spinOne implements AdapterView.OnItemSelectedListener
{
int ide;
spinOne(int i)
{
ide =i;
}
public void onItemSelected(AdapterView<?> parent, View view,
int index, long id) {
if(ide == 1)
from = index;
else if(ide == 2)
to = index;
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
}
CurrencyConverter.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFFFFF"
>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#FFFFFF">
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/one"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/in"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Spinner
android:id="#+id/spinner2"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/equal"
android:textAppearance="?android:attr/textAppearanceLarge" />
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="match_parent"
android:layout_height="122dp"
android:gravity="center"
android:background="#ffffff">
<RelativeLayout
android:id="#+id/relativeLayout2"
android:layout_width="match_parent"
android:layout_height="120dp"
android:gravity="center"
android:background="#ffffff">
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="#string/result"
android:textSize="35dp"
/>
</RelativeLayout>
</RelativeLayout>
<Button
android:id="#+id/button1"
android:layout_marginTop="10dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/calculate" />
</LinearLayout>
</ScrollView>
Error:
FATAL EXCEPTION: main Process: info.androidhive.customlistviewvolley, PID: 8469
android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
at info.androidhive.customlistviewvolley.model.CurrencyConverter$1.getJson(CurrencyConverter.java:98)
at info.androidhive.customlistviewvolley.model.CurrencyConverter$1.onClick(CurrencyConverter.java:76)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
As it said "NetworkOnMainThreadException" do not hit api direclty instead use AsyncTask for it .
Just define asynctask first
class Calculate extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... args) {
s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22"+val[from]+val[to]+"%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
JSONObject jObj;
jObj = new JSONObject(s);
String exResult = jObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
return null;
}
#Override
protected void onPostExecute(String file_url) {
t.setText(exResult);
}
And call AsyncTask there
if (from == to) {
Toast.makeText(getActivity().getApplicationContext(), "Invalid", 4000).show();
} else {
new Calculate ().excute();
}
Answer:
Updated
CurrencyConverter.java
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import info.androidhive.customlistviewvolley.R;
public class CurrencyConverter extends Fragment {
public CurrencyConverter() {
}
TextView t;
public int to;
public int from;
public String[] val;
public String s;
String exResult;
public Handler handler;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.currency_converter, container, false);
t= (TextView) rootView.findViewById(R.id.textView4);
Spinner s1 = (Spinner) rootView.findViewById(R.id.spinner1);
Spinner s2 = (Spinner) rootView.findViewById(R.id.spinner2);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this.getActivity(), R.array.name, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
val = getResources().getStringArray(R.array.value);
s1.setAdapter(adapter);
s2.setAdapter(adapter);
s1.setOnItemSelectedListener(new spinOne(1));
s2.setOnItemSelectedListener(new spinOne(2));
Button b = (Button) rootView.findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View View) {
if (from == to) {
Toast.makeText(getActivity().getApplicationContext(), "Invalid", 4000).show();
} else {
new calculate().execute();
}
}
});
return rootView;
}
public class calculate extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... args) {
try {
s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22"+val[from]+val[to]+"%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
JSONObject jObj;
jObj = new JSONObject(s);
exResult = jObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return exResult;
}
#Override
protected void onPostExecute(String exResult) {
t.setText(exResult);
}
}
public String getJson(String url)throws IOException {
StringBuilder build = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String con;
while ((con = reader.readLine()) != null) {
build.append(con);
}
return build.toString();
}
public class spinOne implements AdapterView.OnItemSelectedListener
{
int ide;
spinOne(int i)
{
ide =i;
}
public void onItemSelected(AdapterView<?> parent, View view,
int index, long id) {
if(ide == 1)
from = index;
else if(ide == 2)
to = index;
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
}

Unable to get data from query results from Twitter API

I am new to Android. I can't get my ListView to populate. I am aware that this question has been asked on SO multiple times before and I have tried the things suggested in other questions (e.g. making sure my orientation is set to vertical, calling notifyDataSetChanged etc) and it still won't work. My activity class is as follows:
package com.michaelnares.twitterclient;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.*;
import twitter4j.*;
import twitter4j.conf.ConfigurationBuilder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Created by michael on 01/05/2014.
*/
public class SearchActivity extends Activity {
EditText queryEditText = null;
String queryText = null;
private Context context = this;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
queryEditText = (EditText) findViewById(R.id.queryEditText);
queryText = (queryEditText.getText().toString());
final Context context = this;
Button queryButton = (Button) findViewById(R.id.queryButton);
queryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (queryText.equals(null)) {
Toast.makeText(context, "You did not enter a query", Toast.LENGTH_SHORT).show();
} else {
new SearchAsyncTask().execute();
}
}
});
} // ends onCreate()
private class SearchAsyncTask extends AsyncTask<String, String, ArrayList<String>>
{
private ProgressDialog dialog = new ProgressDialog(SearchActivity.this);
private ArrayList<String> searchResults;
#Override
protected void onPreExecute()
{
super.onPreExecute();
dialog.setMessage("Getting data...");
dialog.setIndeterminate(false);
dialog.setCancelable(true);
dialog.show();
}
#Override
protected ArrayList<String> doInBackground(String... strings) {
APIClient client = new APIClient();
searchResults = client.getQueryResults(queryText);
return searchResults;
}
#Override
protected void onPostExecute(ArrayList<String> results)
{
dialog.dismiss();
results.addAll(searchResults);
final ListView searchListView = (ListView) findViewById(R.id.searchListView);
final ArrayAdapter adapter = new ArrayAdapter(context, android.R.layout.simple_list_item_1, results);
adapter.notifyDataSetChanged();
searchListView.setAdapter(adapter);
}
}
} //ends class
and my XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp" >
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/search"
android:textSize="25dp"/>
<EditText android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/queryEditText"
android:ems="20"/>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/query"
android:id="#+id/queryButton"
android:textSize="15dp"/>
<ListView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/searchListView">
</ListView>
</LinearLayout>
Here is my API client class also:
package com.michaelnares.twitterclient;
import android.util.Log;
import twitter4j.*;
import twitter4j.conf.ConfigurationBuilder;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Created by michael on 01/05/2014.
*/
public class APIClient
{
ArrayList<String> statusArrayList = new ArrayList<String>();
ArrayList<String> searchArrayList = new ArrayList<String>();
public ArrayList<String> getHomeTimeline() {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey(AuthConstants.API_KEY)
.setOAuthConsumerSecret(AuthConstants.API_SECRET)
.setOAuthAccessToken(AuthConstants.ACCESS_TOKEN)
.setOAuthAccessTokenSecret(AuthConstants.ACCESS_TOKEN_SECRET);
try {
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
List<Status> statuses = twitter.getHomeTimeline();
statusArrayList.clear();
for (Status status : statuses)
{
statusArrayList.add(status.toString());
}
}
catch (TwitterException e)
{
Log.e(LogConstants.LOG, "Failed to get home timeline tweets: " + e.getErrorMessage());
}
return statusArrayList;
} // ends getHomeTimeline() method
public ArrayList<String> getQueryResults(String userQuery)
{
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey(AuthConstants.API_KEY)
.setOAuthConsumerSecret(AuthConstants.API_SECRET)
.setOAuthAccessToken(AuthConstants.ACCESS_TOKEN)
.setOAuthAccessTokenSecret(AuthConstants.ACCESS_TOKEN_SECRET);
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
searchArrayList.clear();
try {
Query query = new Query(userQuery);
QueryResult result;
result = twitter.search(query);
List<Status> tweets = result.getTweets();
int count = 0;
searchArrayList.clear();
for (Iterator<Status> i = tweets.iterator(); i.hasNext();)
{
Status tweet = i.next();
count++;
if (count == 10)
{
break;
}
searchArrayList.add("#" + tweet.getUser().getScreenName() + " - " + tweet.getText());
} // ends for loop
} // ends try block
catch (TwitterException e)
{
Log.e(LogConstants.LOG, "Failed to search tweets: " + e.getErrorMessage());
}
return searchArrayList;
} // ends getQueryResults() method
} // ends class
I'm really struggling to work out what the issue is.

Android app emulator install fails

I'm having trouble running my Android app in the emulator: I get the same error everytime I try to:
12-12 08:53:33.958: E/cutils-trace(5320): Error opening trace file: No such file or directory (2)
Here is my LoginPage.java code:
EDIT: I changed my .java's code a bit but I keep on getting the above error... I'm sure there's something I'm not fully understanding but I can't see what it is.
LoginPage.java
package com.example.shop;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import com.example.shop.R;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
public class LoginPage extends Activity implements OnClickListener, OnItemSelectedListener {
Context context;
private TextView textView;
EditText username;
EditText password;
String userid;
boolean succeed;
Boolean isInternetPresent;
ConnectionChecker cc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_page);
context=this;
userid = "";
username = (EditText)findViewById(R.id.edittext_login_username);
password = (EditText)findViewById(R.id.edittext_login_password);
textView = (TextView)findViewById(R.id.textView);
cc = new ConnectionChecker(getApplicationContext());
isInternetPresent = false;
//login_button();
Button enter = (Button) findViewById(R.id.enter);
enter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(arg0.getId() == R.id.enter)
{
Toast.makeText(
context,
"Login correcte",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, Tenda.class);
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://www.v2msoft.com/clientes/lasalle/curs-android/login.php" });
startActivity(intent);
finish();
}
if (username.getText().toString().equals("luis") && password.getText().toString().equals("seguro")){
Toast.makeText(getApplicationContext(), "Redirecting...",
Toast.LENGTH_SHORT).show();
succeed = true;
userid = "luis";
}
else{
Toast.makeText(getApplicationContext(), "Wrong info",
Toast.LENGTH_SHORT).show();
succeed = false;
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login_page, menu);
return true;
}
public void login ()
{
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
textView.setText(result);
}
}
public void login_button()
{
}
public void IC (View v)
{
isInternetPresent = cc.isConnectingToInternet();
// check for Internet status
if (isInternetPresent) {
// Internet Connection is Present
// make HTTP requests
showAlertDialog(LoginPage.this, "Internet Connection",
"You have internet connection", true);
} else {
// Internet connection is not present
// Ask user to connect to Internet
showAlertDialog(LoginPage.this, "No Internet Connection",
"You don't have internet connection.", false);
}
}
#SuppressWarnings("deprecation")
public void showAlertDialog(Context context, String title, String message, Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
And, also, my .xml file:
activity_login_page.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".LoginPage" >
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
></TextView>
<EditText
android:id="#+id/edittext_login_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="username"
android:inputType="text"/>
<EditText
android:id="#+id/edittext_login_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="password"
android:password="true"
android:layout_below="#+id/edittext_login_username"
/>
<Button
android:id="#+id/enter"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_gravity="right"
android:text="login"
android:layout_below="#+id/edittext_login_password" />
</RelativeLayout>
Anyone could pinpoint to me where my mistake is?
First move this onCreate() method.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_page);
context=this;
EditText username = (EditText)findViewById(R.id.edittext_login_username);
EditText password = (EditText)findViewById(R.id.edittext_login_password);
login_button();
}
Because you can't initialize your UI element before onCreate() method.
Also you have just declare your
private TextView textView;
but not initialize it means didn't find ID for it. So do that also.
do this first
public class LoginPage extends Activity implements OnClickListener, OnItemSelectedListener {
Context context;
private TextView textView;
EditText username ;
EditText password ;
String userid;
boolean succeed;
ConnectionChecker cc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_page);
context=this;
username = (EditText)findViewById(R.id.edittext_login_username);
password = (EditText)findViewById(R.id.edittext_login_password);
String userid = "";
Boolean isInternetPresent = false;
ConnectionChecker cc = new ConnectionChecker(getApplicationContext());
login_button();
}
}

Android login screen with internet connection install error

I'm working on a login screen in Android which connects to Internet so as to check that the username and the password are correct.
LoginScreen.java
package com.example.shop;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import com.example.shop.R;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
public class LoginPage extends Activity implements OnClickListener, OnItemSelectedListener {
Context context;
private TextView textView;
EditText username;
EditText password;
String userid;
boolean succeed;
Boolean isInternetPresent;
ConnectionChecker cc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_page);
context=this;
userid = "";
username = (EditText)findViewById(R.id.edittext_login_username);
password = (EditText)findViewById(R.id.edittext_login_password);
textView = (TextView)findViewById(R.id.textView);
cc = new ConnectionChecker(getApplicationContext());
isInternetPresent = false;
//login_button();
Button enter = (Button) findViewById(R.id.enter);
enter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(arg0.getId() == R.id.enter)
{
Toast.makeText(
context,
"Login correcte",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, Tenda.class);
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://www.v2msoft.com/clientes/lasalle/curs-android/login.php" });
startActivity(intent);
finish();
}
if (username.getText().toString().equals("luis") && password.getText().toString().equals("seguro")){
Toast.makeText(getApplicationContext(), "Redirecting...",
Toast.LENGTH_SHORT).show();
succeed = true;
userid = "luis";
}
else{
Toast.makeText(getApplicationContext(), "Wrong info",
Toast.LENGTH_SHORT).show();
succeed = false;
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login_page, menu);
return true;
}
public void login ()
{
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
textView.setText(result);
}
}
public void login_button()
{
}
public void IC (View v)
{
isInternetPresent = cc.isConnectingToInternet();
// check for Internet status
if (isInternetPresent) {
// Internet Connection is Present
// make HTTP requests
showAlertDialog(LoginPage.this, "Internet Connection",
"You have internet connection", true);
} else {
// Internet connection is not present
// Ask user to connect to Internet
showAlertDialog(LoginPage.this, "No Internet Connection",
"You don't have internet connection.", false);
}
}
#SuppressWarnings("deprecation")
public void showAlertDialog(Context context, String title, String message, Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
And my layout:
activity_login_page
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".LoginPage" >
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
></TextView>
<EditText
android:id="#+id/edittext_login_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="username"
android:inputType="text"/>
<EditText
android:id="#+id/edittext_login_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="password"
android:password="true"
android:layout_below="#+id/edittext_login_username"
/>
<Button
android:id="#+id/enter"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_gravity="right"
android:text="login"
android:layout_below="#+id/edittext_login_password" />
</RelativeLayout>
The problem is that, when I try to run it with the emulator, I get the following error:
12-12 09:24:54.808: E/cutils-trace(5407): Error opening trace file: No such file or directory (2)
Can anyone help me figure out my mistake?
you are using a different name of your layout activity_login_page
setContentView(R.layout.activity_login_page);
but your layout is activity_login_screen
change it to
setContentView(R.layout.activity_login_screen);

Categories

Resources