I am trying to call another class from a class using intent but when i click the button it is made to force close the application and when i tried to debug it,it shows an error source not found.
code is :
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),RegistrationActivity.class);
startActivity(i);
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),SearchDirectly1Activity.class);
startActivity(i);
}
});
main activity xml code is::
<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=".MainActivity" >
<TextView
android:id="#+id/t1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="#string/Donate" />
<ImageView
android:id="#+id/i1"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_marginTop="20dp"
android:layout_below="#id/t1"
android:src="#drawable/ic_launcher"
/>
<Button
android:id="#+id/b2"
android:layout_width="150dp"
android:layout_height="50dp"
android:layout_alignRight="#+id/t1"
android:layout_below="#+id/i1"
android:layout_marginTop="41dp"
android:text="#string/searching" />
<Button
android:id="#+id/b1"
android:layout_width="150dp"
android:layout_height="50dp"
android:layout_alignBaseline="#+id/b2"
android:layout_alignBottom="#+id/b2"
android:layout_toLeftOf="#+id/b2"
android:text="#string/register" />
</RelativeLayout>
and main activity class is::
package donor.android.blooddonor;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
Button b1;
Button b2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//buttons
b1=(Button) findViewById (R.id.b1);
b2=(Button) findViewById (R.id.b2);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),RegistrationActivity.class);
startActivity(i);
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),SearchDirectly1Activity.class);
startActivity(i);
}
});
}
}
registrationactivity xml is::
package donor.android.blooddonor;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class RegistrationActivity extends Activity{
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText et1;
EditText et2;
EditText et3;
EditText et4;
EditText et5;
EditText et6;
private static String url_create_donor = "http://127.0.0.1/android_connect/create_donor.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.registration);
// Edit Text
et1 = (EditText) findViewById (R.id.et1);
et2 = (EditText) findViewById (R.id.et2);
et3 = (EditText) findViewById (R.id.et3);
et4 = (EditText) findViewById (R.id.et4);
et5 = (EditText) findViewById (R.id.et5);
et6 = (EditText) findViewById (R.id.et6);
// Create button
Button b2 = (Button) findViewById (R.id.b2);
// button click event
b2.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view) {
// creating new donor in background thread
new CreateDonor1().execute();
}
});
}
class CreateDonor1 extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(RegistrationActivity.this);
pDialog.setMessage("Creating DONOR..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
String NAME = et1.getText().toString();
String ADDRESS = et2.getText().toString();
String PHONENUMBER = et3.getText().toString();
String EMAIL = et4.getText().toString();
String CITY = et5.getText().toString();
String BLOODGROUP = et6.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("NAME", NAME));
params.add(new BasicNameValuePair("ADDRESS", ADDRESS));
params.add(new BasicNameValuePair("PHONENUMBER", PHONENUMBER));
params.add(new BasicNameValuePair("EMAIL", EMAIL));
params.add(new BasicNameValuePair("CITY", CITY));
params.add(new BasicNameValuePair("BLOODGROUP", BLOODGROUP));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_donor,
"POST", params);
Log.d("Create Response", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created donor
Intent i = new Intent(getApplicationContext(), SuccessfulActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
pls check the answer by commonsware in the below link
When to call activity context OR application context?
public class MainActivity extends Activity implements OnClickListener
Then in onCreate
Button b1 = (Button) findViewById(R.id.b1);
Button b2 = (Button) findViewById(R.id.b2);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
Then override onClick
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.b1 :
Intent i=new Intent(MainActivity.this,RegistrationActivity.class);
startActivity(i);
break;
case R.id.b2 :
Intent i=new Intent(MainActivity.this,SearchDirectly1Activity.class);
startActivity(i);
break;
}
}
Or
In onCreate using annonymous inner class
Button b1 = (Button) findViewById(R.id.b1);
Button b2 = (Button) findViewById(R.id.b2);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(MainActivity.this,RegistrationActivity.class);
startActivity(i);
}
});
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(MainActivity.this,SearchDirectly1Activity.class);
startActivity(i);
}
});
Make sure you have made an entry for the activities in manifest file
Do not use ApplicationContext to start activity,because application context do not ensure which activity task will use,and will throw Exception.
So you need to use Activity Context or Context from view(someView.getContext()) to start activity.
You may want to check the below link
When to call activity context OR application context?
Related
I currently working with a project and stuck on the radio button which getting only the checked radio in xml, I search many case regarding with this concern and still got the same problem.
here is the activity which toasting only the checked radio in xml
package com.example.kapoyei.hatidtubiganapp;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.example.kapoyei.hatidtubiganapp.helper.Http;
import com.example.kapoyei.hatidtubiganapp.helper.Network;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
public class ClientActivity extends Activity implements View.OnClickListener {
public static String jsonObject;
SharedPreferences sharedPref;
Intent i;
Button btnLogout, btnBreakPoint;
Spinner spnStation;
ImageView btnReserve, btnStationList, btnPending, btnHistory;
TextView txtSelectDate;
EditText no_container;
RadioGroup radioGroup;
RadioButton radioButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client);
btnLogout = (Button) findViewById(R.id.btnLogout);
btnReserve = (ImageView) findViewById(R.id.btnReserve);
btnStationList = (ImageView) findViewById(R.id.btnStation);
btnPending = (ImageView) findViewById(R.id.btnPending);
btnHistory = (ImageView) findViewById(R.id.btnHistory);
btnPending.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
i = new Intent(ClientActivity.this, PendingClientOrderActivity.class);
startActivity(i);
}
});
btnStationList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
i = new Intent(ClientActivity.this, StationList.class);
startActivity(i);
}
});
btnReserve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(ClientActivity.this);
LayoutInflater inflater = getLayoutInflater();
view = inflater.inflate(R.layout.layout_dialog_reserve, null);
spnStation = (Spinner) view.findViewById(R.id.spnStation);
txtSelectDate = (TextView) view.findViewById(R.id.txtDate);
no_container = (EditText) view.findViewById(R.id.etContainer);
radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup);
radioButton = (RadioButton) view.findViewById(radioGroup.getCheckedRadioButtonId());
btnBreakPoint = (Button) view.findViewById(R.id.btnBreakPoint);
final Calendar c = Calendar.getInstance();
final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, day);
String dateFormat = "MM/dd/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat, Locale.US);
txtSelectDate.setText(sdf.format(c.getTime()));
}
};
txtSelectDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new DatePickerDialog(ClientActivity.this,
date,
c.get(Calendar.YEAR),
c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH)).show();
}
});
btnBreakPoint.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(no_container.getText().toString().isEmpty() || txtSelectDate.getText().toString().equalsIgnoreCase("-- CLICK TO DATE DELIVER --")) {
Toast.makeText(getApplicationContext(), "All fields require", Toast.LENGTH_SHORT).show();
} else {
/*Bundle bundle = new Bundle();
bundle.putString("station", spnStation.getSelectedItem().toString());
bundle.putString("date", txtSelectDate.getText().toString());
bundle.putString("no_container", no_container.getText().toString());
bundle.putString("type", Integer.toString(radioGroup.getCheckedRadioButtonId()));
i = new Intent(ClientActivity.this, CheckOut.class);
i.putExtras(bundle);
startActivity(i);*/
String typeOrder = radioButton.getText().toString();
Toast.makeText(getApplicationContext(), typeOrder, Toast.LENGTH_LONG).show();
}
}
});
Network network = new Network(getApplicationContext());
if(network.isNetwork()) {
new ClientActivity.GetStationList().execute();
} else {
Toast.makeText(getApplicationContext(), "Coud not get stations", Toast.LENGTH_SHORT).show();
}
builder.setView(view);
builder.setCancelable(true);
AlertDialog dialog = builder.create();
dialog.show();
}
});
btnHistory.setOnClickListener(this);
btnLogout.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if(view.getId() == R.id.btnLogout) {
finish();
sharedPref = getSharedPreferences("ht", MODE_PRIVATE);
SharedPreferences.Editor modify = sharedPref.edit();
modify.putBoolean("login", false);
modify.putString("id", "");
modify.putString("auth", "");
modify.apply();
i = new Intent(ClientActivity.this, LoginActivity.class);
startActivity(i);
}
if(view.getId() == R.id.btnHistory) {
i = new Intent(ClientActivity.this, HistoryActivity.class);
startActivity(i);
}
}
public class GetStationList extends AsyncTask<Void, Void, String> {
ProgressDialog pd;
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(ClientActivity.this);
pd.setMessage("Getting station ...");
pd.setCancelable(false);
pd.show();
}
#Override
protected void onPostExecute(String result) {
pd.cancel();
json(result);
}
#Override
protected String doInBackground(Void... voids) {
String data = "";
jsonObject = "";
try {
String link = (String) Http.url + "?type=getstationlist";
URL getURL = new URL(link);
HttpURLConnection httpURLConnection = (HttpURLConnection) getURL.openConnection();
httpURLConnection.setReadTimeout(10000);
httpURLConnection.setConnectTimeout(15000);
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setDoInput(true);
httpURLConnection.connect();
InputStream is = (InputStream) httpURLConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
while((data = reader.readLine()) != null) {
jsonObject += data;
}
Log.i("", jsonObject);
return jsonObject;
} catch(Exception e) {
e.printStackTrace();
}
return null;
}
public void json(String json) {
List<String> collectionName = new ArrayList<>();
if(json != null) {
try {
JSONObject jobj = new JSONObject(json);
JSONArray jarray = jobj.getJSONArray("stationlist");
String name = "";
String id = "";
for(int i = 0; i < jarray.length(); i++) {
JSONObject obj = jarray.getJSONObject(i);
name = obj.getString("name");
collectionName.add(name);
}
ArrayAdapter<String> adapter = new ArrayAdapter<>(getBaseContext(), android.R.layout.simple_list_item_1, collectionName);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnStation.setAdapter(adapter);
} catch(Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "Connection problem", Toast.LENGTH_SHORT).show();
}
}
}
}
and here is the xml where located the layout of my radio
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="20dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select Station"
android:layout_margin="10dp"
android:textSize="20sp"/>
<Spinner
android:id="#+id/spnStation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Date"
android:layout_margin="10dp"
android:textSize="20sp"/>
<TextView
android:id="#+id/txtDate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="-- CLICK TO DATE DELIVER --"
android:textSize="15sp"
android:layout_margin="10dp"
android:layout_gravity="center"
android:textAlignment="center"/>
<EditText
android:id="#+id/etContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="No. Of Containers"
android:layout_margin="10dp"/>
<RadioGroup
android:id="#+id/radioGroup"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RadioButton
android:id="#+id/Gallon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Gallon"
android:checked="true"/>
<RadioButton
android:id="#+id/Litre"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Litre" />
</RadioGroup>
<Button
android:id="#+id/btnBreakPoint"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_margin="10dp"
android:text="Proceed to Check Out" />
</LinearLayout>
</RelativeLayout>
You can apply the below codes:
int radioid = radioButtonGroup.getCheckedRadioButtonId();
View radio_button= radioButtonGroup.findViewById(radioButtonID);
int index = radioButtonGroup.indexOfChild(radioButton);
If the RadioGroup contains other Views (like a TextView) then the indexOfChild() method will return wrong index.
To get selected RadioButton Text on RadioGroup follow the below code:
RadioButton radio = (RadioButton) radioButtonGroup.getChildAt(index);
String text = radio.getText().toString();
Why this is happened? Because before you click Break Point button, you change the radio button id but not bind it to your variable, your variable still storing the old value. You need to add this code
radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup);
radioButton = (RadioButton) view.findViewById(radioGroup.getCheckedRadioButtonId());
above
String typeOrder = radioButton.getText().toString();
so it will shown
btnBreakPoint.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
...
radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup);
radioButton = (RadioButton) view.findViewById(radioGroup.getCheckedRadioButtonId());
String typeOrder = radioButton.getText().toString();
...
}
or you can move the scope of radioGroup assignment to onCreate scope
I have developed a layout which has 2 textboxes and 1 button. At the first, the button is appear and two textboxes are disappeared. However, I dont know how can I change the visibility of textboxes and other components to appear when the insert button is pressed. Please explain simply because I am new in android.
<LinearLayout 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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:orientation="vertical"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".Main3Activity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:id="#+id/textView"
android:visibility="gone" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editTextName"
android:visibility="gone" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Address"
android:id="#+id/textView2"
android:visibility="gone" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editTextAddress"
android:visibility="gone" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Insert"
android:onClick="insert"
android:id="#+id/button" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textViewResult" />
</LinearLayout>
Main2Activity
package com.example.alan.mainactivity;
import org.apache.http.util.EntityUtils;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
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 org.apache.http.params.BasicHttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.view.View;
import android.widget.Toast;
import android.view.View.OnClickListener;
public class Main2Activity extends ActionBarActivity {
public static final String USER_NAME1 = "USERNAME";
String myJSON;
private EditText editTextName;
private EditText editTextAdd;
private static final String TAG_RESULTS="result";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_ADD ="address";
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList;
ListView list;
Button btn_insert=(Button)findViewById(R.id.button);
btn_insert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView textView= (TextView)findViewById(R.id.textView);
textView.setVisibility(View.VISIBLE);
//Similarly the other views.....
}
});
public void insert(View view){
String name = editTextName.getText().toString();
String add = editTextAdd.getText().toString();
insertToDatabase(name, add);
}
private void insertToDatabase(String name, String add){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String paramUsername = params[0];
String paramAddress = params[1];
String name = editTextName.getText().toString();
String add = editTextAdd.getText().toString();
Intent intent = getIntent();
String username = intent.getStringExtra(MainActivity.USER_NAME).toString();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name", name));
nameValuePairs.add(new BasicNameValuePair("address", add));
nameValuePairs.add(new BasicNameValuePair("user", username));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(
"http://www.oobac.com/app/insert-db.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return "success";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
TextView textViewResult = (TextView) findViewById(R.id.textViewResult);
textViewResult.setText("Inserted");
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(name, add);
}
//-----------------------
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
Intent intent = getIntent();
String username = intent.getStringExtra(MainActivity.USER_NAME);
editTextName = (EditText) findViewById(R.id.editTextName);
editTextAdd = (EditText) findViewById(R.id.editTextAddress);
TextView textView = (TextView) findViewById(R.id.textView3);
textView.setText("Welcome " + username);
list = (ListView) findViewById(R.id.listView);
personList = new ArrayList<HashMap<String,String>>();
getData();
}
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String address = c.getString(TAG_ADD);
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_ID,id);
persons.put(TAG_NAME,name);
persons.put(TAG_ADD,address);
personList.add(persons);
}
ListAdapter adapter = new SimpleAdapter(
Main2Activity.this, personList, R.layout.list_item,
new String[]{TAG_ID,TAG_NAME,TAG_ADD},
new int[]{R.id.id, R.id.name, R.id.address}
);
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
//--------------------------------------------
Intent intent = getIntent();
String username = intent.getStringExtra(MainActivity.USER_NAME);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", username));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.oobac.com/app/amir.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse response = httpclient.execute(httppost);
String st = EntityUtils.toString(response.getEntity());
Log.d("TK SUPPORT", "In the try Loop" + st);
myJSON = st;
} catch (Exception e) {
Log.d("TK SUPPORT", "Connection Error : " + e.toString());
}
return "OK";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
#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);
}
}
SAMPLE SNIPPET
replace your onCreate method to this method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
Intent intent = getIntent();
String username = intent.getStringExtra(MainActivity.USER_NAME);
editTextName = (EditText) findViewById(R.id.editTextName);
editTextAdd = (EditText) findViewById(R.id.editTextAddress);
TextView textView = (TextView) findViewById(R.id.textView3);
Button btn_insert=(Button)findViewById(R.id.button);
btn_insert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView textView= (TextView)findViewById(R.id.textView);
textView.setVisibility(View.VISIBLE);
//Similarly the other views.....
}
});
textView.setText("Welcome " + username);
list = (ListView) findViewById(R.id.listView);
personList = new ArrayList<HashMap<String,String>>();
getData();
}
Try this:
EditText name = (EditText)findViewById(R.id.editTextName);
name.setVisibility(View.GONE);
Declare a class variable like this
private TextView yourTextView;
You should get the instance of your TextView like this
yourTextView = (TextView)findViewById(R.id.your_editText);
Then on button click, setVisibility to visible
Button mButton = (Button)findViewById(R.id.m_button);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
yourTextView.setVisibility(View.VISIBLE);
}
});
To hide, setVisibility to Gone
yourTextView.setVisibility(View.GONE);
Use the setVisibility property to hide your views.
yourView.setVisibility(View.GONE);
View.GONE This view is invisible, and it doesn't take any space for layout purposes.
Also
yourView.setVisibility(View.INVISIBLE);
View.INVISIBLE This view is invisible, but it still takes up space for layout purposes.
Button btn_insert=(Button)findViewById(R.id.button);
btn_insert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView textView= (TextView)findViewById(R.id.textView);
textView.setVisibility(View.VISIBLE);
//Similarly the other views.....
}
});
Firstly, You are setting android:onClick="insert" in layout xml and you are also setting click listener in onCreate method too. So either remove from xml or onCreate listener. Secondly, in onClick, TextView textView=
(TextView)findViewById(R.id.textView);
textView.setVisibility(View.VISIBLE);
Hope this helps.
In Simple way Just put your onClicklistener() of button inside onCreate() method like this ..
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
Intent intent = getIntent();
String username = intent.getStringExtra(MainActivity.USER_NAME);
editTextName = (EditText) findViewById(R.id.editTextName);
editTextAdd = (EditText) findViewById(R.id.editTextAddress);
TextView textView = (TextView) findViewById(R.id.textView3);
Button btn_insert=(Button)findViewById(R.id.button);
btn_insert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView textView= (TextView)findViewById(R.id.textView);
textView.setVisibility(View.VISIBLE);
//do it here whatever u want to do on press of button
//Similarly the other views.....
}
});
textView.setText("Welcome " + username);
list = (ListView) findViewById(R.id.listView);
personList = new ArrayList<HashMap<String,String>>();
getData();
}
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();
}
}
I have an app, which consists of a tabhost. I am using a AsyncTask to perform some internet work in the background. Now in the onPostExecute, I want it to start a new activity. When I create a new intent, the new activity is shown, but there are no tabs.. it's just the activity.
Now i've read online how to do this, And i've managed to get into the right direction i think. This is the entire code:
package com.appsoweb.kvodeventer;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ActivityGroup;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class KVOMeldingen extends ActivityGroup {
public static final JSONObject jsonResult = null;
Button bLogin, bCreateAccount, bResetPassword;
EditText etUsername, etPassword;
static String Username;
static String Password;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.meldingen);
final EditText etUsername = (EditText) findViewById(R.id.etUsername);
final EditText etPassword = (EditText) findViewById(R.id.etPassword);
Button bLogin = (Button) findViewById(R.id.bLogin);
Button bCreateAccount = (Button) findViewById(R.id.bCreateAccount);
Button bResetPassword = (Button) findViewById(R.id.bResetPassword);
bLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (etUsername.length() <= 0) {
etUsername.setError("Veld mag niet leeg zijn");
} else if (etPassword.length() <= 0) {
etPassword.setError("Veld mag niet leeg zijn");
} else {
Username = etUsername.getText().toString();
Password = etPassword.getText().toString();
}
LoginTask NDLT = new LoginTask();
NDLT.execute();
}
});
bCreateAccount.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Doe iets hier.......
}
});
bResetPassword.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Doe iets hier........
}
});
}
public static String getUsername() {
return Username;
}
public static String getPassword() {
return Password;
}
class LoginTask extends AsyncTask<Void, Void, JSONObject> {
ProgressDialog waitingDialog;
#Override
protected void onPreExecute() {
waitingDialog = new ProgressDialog(KVOMeldingen.this);
waitingDialog.setMessage("Laden...");
waitingDialog.show();
super.onPreExecute();
}
#Override
protected JSONObject doInBackground(Void... params) {
JSONObject json = JsonFunctionLogin
.getJsonLoginResult("http://api.crossalertdeventer.nl/login.json");
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
super.onPostExecute(json);
if (waitingDialog.isShowing()) {
waitingDialog.dismiss();
Log.d("iets gebeurt", "gedaan");
}
try {
String LoginResult = json.getString("login");
String UserIdResult = json.getString("user_id");
Log.d("LoginResult", LoginResult);
Log.d("LoginUserId", UserIdResult);
json = null;
Intent intent = new Intent(KVOMeldingen.this, KVOCards.class);
View view = getLocalActivityManager().startActivity("KVOCards", intent
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();
replaceView(view);
} catch (Exception e) {
Log.e("KVOMeldingen", "error" + e.getMessage());
}
}
public void replaceView(View v){
setContentView(v);
}
}
}
As you can see: I've created a View that will be shown trough an Intent. But the intent doesn't launch after the onbackground. It gives me an error:
Unable to start Activity componentInfo Unable to add window ... Token..... is not valid... Is your application running?
What am i doing wrong?
Thnx in advance
Starting a new Activity means you are navigating from your TabActivity to a normal Activity. Obviously you can't find a tab in Activity. You have to replace views instead of creating Activities.
Here is a good example of how to use ActivityGroup with TabActivity.
http://web.archive.org/web/20100816175634/http://blog.henriklarsentoft.com/2010/07/android-tabactivity-nested-activities/
But still this approach has been deprecated. You might have to consider using fragments though.
Take a look here, http://developer.android.com/resources/samples/Support4Demos/src/com/example/android/supportv4/app/FragmentTabs.html
i am working with my project and i find it hard to go to my main activity which is diary after I log-in..The problem is that I can't display a message saying I successfully logged in and after that proceed to creating my diary..what should I do? here's my code..
login.class
package com.gomez.android;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class login extends Activity{
//Declare views
private EditText uname;
private EditText pword;
private Button btnlogin;
private Button btncancel;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set Activity Layout
setContentView(R.layout.login);
//Get EditText and Button References
uname = (EditText)findViewById(R.id.username);
pword = (EditText)findViewById(R.id.password);
btnlogin = (Button)findViewById(R.id.login_enter);
btncancel = (Button)findViewById(R.id.cancel);
//set Click Listener
btnlogin.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Check Login
final String username = uname.getText().toString();
final String password = pword.getText().toString();
try{
if(username.length()>0&& password.length()>0)
{
dbuser users = new dbuser(login.this);
users.open();
if (users.Login(username, password))
{
Toast.makeText(login.this,"Successfully Logged In", Toast.LENGTH_LONG).show();
Intent i = new Intent(login.this, firstpage.class);
startActivity(i);
}
else{
Toast.makeText(login.this,"Invalid Username/Password", Toast.LENGTH_LONG).show();
}
users.close();
}
}catch(Exception e)
{
Toast.makeText(login.this,e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
btncancel.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
//close application
finish();
}
});
}
}
please help me..thanks
You can use Asynctask class
Asynctask
In the onPostExecute method, you can show your notification then start your activity.