Hello I am new to Android, but reading as much as possible;
I create an APP for entering Trip Reports from Trucking. I have the form corrected, but using VAL1-VAL2, then trying to send that using "registerAPI" is giving me failures.
So created RegisterAPI class of
public interface RegisterAPI {
#FormUrlEncoded
#POST("/insert.php")
public void insertUser(
#Field("trucksID") String trucksID,
#Field("tripReportNumber") String tripReportNumber,
#Field("enteredDate") String enteredDate,
#Field("emptyMilage") String emptyMilage,
#Field("loadedMilage") String loadedMilage,
#Field("estTotal") String estTotal,
Callback<Response> callback);
Then in the MainActivity:
//Class for our main activity with OnClickListener
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
//Declaring views
private WebView webView;
private EditText trucksID;
private EditText tripReportNumber;
private EditText enteredDate;
private EditText emptyMilage;
private EditText loadedMilage;
private Button buttonRegister;
private String estTotal;
private String estMilage;
//This is our root url
public static final String ROOT_URL = "http://hosturl/php/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initializing Views
trucksID = (EditText) findViewById(R.id.trucksID);
tripReportNumber = (EditText) findViewById(R.id.tripReportNumber);
enteredDate = (EditText) findViewById(R.id.enteredDate);
emptyMilage= (EditText) findViewById(R.id.emptyMilage);
loadedMilage = (EditText) findViewById(R.id.loadedMilage);
buttonRegister = (Button) findViewById(R.id.buttonRegister);
//Adding listener to button
buttonRegister.setOnClickListener(this);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.openWebsite:
Intent website = new Intent(this,ourWebsite.class);
this.startActivity(website);
return true;
case R.id.goto2:
Intent activity2 = new Intent(this,MainActivity2.class);
this.startActivity(activity2);
return true;
case R.id.about_us:
Intent about = new Intent(this,aboutUs.class);
this.startActivity(about);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void insertUser(){
//Here we will handle the http request to insert user to mysql db
//Creating a RestAdapter
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(ROOT_URL) //Setting the Root URL
.build(); //Finally building the adapter
//Creating object for our interface
RegisterAPI api = adapter.create(RegisterAPI.class);
//Defining the method insertuser of our interface
api.insertUser(
//Passing the values by getting it from editTexts
trucksID.getText().toString(),
tripReportNumber.getText().toString(),
enteredDate.getText().toString(),
emptyMilage.getText().toString(),
loadedMilage.getText().toString(),
//can take this out below
estTotal,
//Creating an anonymous callback
new Callback<Response>() {
#Override
public void success(Response result, Response response) {
//On success we will read the server's output using bufferedreader
//Creating a bufferedreader object
BufferedReader reader = null;
//An string to store output from the server
String output = "";
try {
//Initializing buffered reader
reader = new BufferedReader(new InputStreamReader(result.getBody().in()));
//Reading the output in the string
output = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
//Displaying the output as a toast
Toast.makeText(MainActivity.this, output, Toast.LENGTH_LONG).show();
}
#Override
public void failure(RetrofitError error) {
//If any error occured displaying the error as toast
Toast.makeText(MainActivity.this, error.toString(),Toast.LENGTH_LONG).show();
}
}
);
}
//Overriding onclick method
#Override
public void onClick(View v) {
//Calling insertUser on button click
insertUser();
int value1=Integer.parseInt(emptyMilage.getText().toString());
int value2=Integer.parseInt(loadedMilage.getText().toString());
int estMilage=value2-value1;
Toast.makeText(this, "Estimated Milage:"+String.valueOf(estMilage), Toast.LENGTH_SHORT).show();
}
}
Here is the activity_main.xml i am using:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/logoview"
android:src="#mipmap/platelogo"
android:contentDescription="#string/atrixlogo"
android:maxHeight="55dp"
android:minHeight="55dp"
android:minWidth="55dp"
android:maxWidth="55dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true" />
<TextView
android:text="Enter Truck ID:"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/trucksID"
android:inputType="number"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:text="Enter Trip Report Number:"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/tripReportNumber"
android:inputType="number"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:text="Enter Trip Date:"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/enteredDate"
android:inputType="date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="MM/DD/YY" />
<TextView
android:text="Enter Empty Milage:"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/emptyMilage"
android:inputType="number"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:text="Enter Loaded Milage:"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/loadedMilage"
android:inputType="date"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/buttonRegister"
android:text="Submit Trip Report"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
But all i am seeing is the Toast, not carrying forward and inserting the estTotal into the Database onClick
When I run message:
Error:(112, 25) error: cannot find symbol method getText()
Error:(102, 12) error: method insertUser in interface RegisterAPI cannot be applied to given types;
required: String,String,String,String,String,String,Callback<Response>
found: String,String,String,String,String,<anonymous Callback<Response>>
reason: actual and formal argument lists differ in length
If i take out the estTotal.gettext from the Mainactivity and RegisterAPI no errors on running.
I have been looking at a lot of the StackOverflow's but most of those are on one intent or one activity. Any help would be awesome.
The problem is here: estTotal.getText().toString() - because you are trying to call method getText() on estTotal - but estTotal is type String, not EditText or TextView - this is how you declared it private String estTotal;.
So removing the line estTotal.getText().toString() should solve the problem. What are you using estTotal for anyway?
I hope this helps.
Related
So I am creating an android application which opens the url entered by the user. Now each time an url is entered by the user, it needs to be save using the "save" button and the save list is seen using the "list" button.
This is my XML file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/content_main"
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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.application.mota_app.MainActivity"
tools:showIn="#layout/activity_main">
<TextView
android:text="#string/enter_the_url_below"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/enter_URL"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="26dp"
android:textSize="19sp"
android:textColor="#android:color/holo_green_dark" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/txtbox_website"
android:layout_marginTop="18dp"
android:width="300dp"
android:inputType="textUri"
android:layout_below="#+id/enter_URL"
android:layout_centerHorizontal="true" />
<Button
android:text="#string/save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn_save"
android:textColor="#color/colorAccent"
android:onClick="save"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Button
android:text="#string/visit"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="#+id/btn_visit"
android:textColor="#android:color/holo_blue_dark"
android:onClick="open"
android:layout_marginBottom="50dp"
android:layout_alignBottom="#+id/btn_save"
android:layout_centerHorizontal="true" />
<Button
android:text="#string/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn_list"
android:onClick="list"
android:textColor="?android:attr/colorPressedHighlight"
android:layout_below="#+id/btn_save"
android:layout_alignLeft="#+id/btn_save"
android:layout_alignStart="#+id/btn_save" />
</RelativeLayout>
This is the XML for the second Activity which will be opened when the list button is clicked:
<?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">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/show"
android:scrollbars="horizontal|vertical"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="63dp" />
<TextView
android:text="#string/list_of_saved_url_s"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="23dp"
android:id="#+id/textView"
android:textColor="#color/colorAccent"
android:textSize="24sp" />
</RelativeLayout>
This is my main class:
public class MainActivity extends AppCompatActivity {
private EditText url;
private Button save;
ArrayList<String> addArray = new ArrayList<String>();
private Button list;
private ListView show1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
url = (EditText)findViewById(R.id.txtbox_website);
save = (Button)findViewById(R.id.btn_save);
list = (Button)findViewById(R.id.btn_list);
show1 = (ListView)findViewById(R.id.show);
}
public void open(View view){
if (url.getText().toString().matches("")) {
Toast.makeText(getApplicationContext(), "Enter a website to open!", Toast.LENGTH_SHORT).show();
return;
}
if (!url.getText().toString().startsWith("http://") && !url.getText().toString().startsWith("https://"))
{
url.setText("http://" + url.getText().toString());
}
if (!Patterns.WEB_URL.matcher(url.getText().toString()).matches())
{
Toast.makeText(getApplicationContext(), "Invalid URL!", Toast.LENGTH_SHORT).show();
url.setError("Enter a valid URL");
url.setText("");
url.setSelection(0);
return;
}
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url.getText().toString()));
startActivity(browserIntent);
}
public void save(View view) {
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String getInput = url.getText().toString();
if(addArray.contains(getInput))
{
Toast.makeText(getBaseContext(), "URL already added to the list!", Toast.LENGTH_LONG).show();
}
else if(getInput == null || getInput.trim().equals(""))
{
Toast.makeText(getBaseContext(), "Input field is empty!", Toast.LENGTH_LONG).show();
}
else{
addArray.add(getInput);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, addArray);
show1.setAdapter(adapter);
((EditText)findViewById(R.id.txtbox_website)).setText("");
}
}
});
}
public void list(View view) {
list.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent screen = new Intent(MainActivity.this, Activity2.class);
startActivity(screen);
}
});
}
#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;
}http://www.stackoverflow.com
return super.onOptionsItemSelected(item);
}
}
My save button and list button is not able to save and list the URLs entered by the user.
What should I add?
Thanks
1) Not Saving:
Currently you are storing data statically inside your addArray object. Which gets cleared when you close app.
I think better to use persist data storage. So you can retrieve already stored websites when app re-launched. (Like browser manages history). Available storage options
2) Not showing list:
You need to pass your current list of urls (i.e. addArray variable) in bundle when starting Activity2 And read that list inside Activity2 onCreate. Find here.
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, addArray);
show1.setAdapter(adapter);
You don't need this list adapter inside your main activity, You need to create it inside Activity2 and set this adapter in your listview.
I hope it will help you fix your issues.
Is it possible to change the location of the button on the dialog to the outside of the dialog itself? something like this (the red squares are buttons):
I know I can get the button with :
dialog.getButton(AlertDialog.BUTTON_NEGATIVE)
but I couldn't find on the manual the way to change it's location.
<?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:gravity="center"
android:padding="20dp"
android:background="#00000000">
<LinearLayout
android:background="#drawable/border_background"
android:layout_gravity="center"
android:gravity="center"
android:padding="20dp"
android:layout_width="match_parent"
android:layout_height="200dp"
android:orientation="vertical">
<TextView
android:layout_width="250dp"
android:layout_height="wrap_content"
android:text="#string/update_app"
android:textSize="18sp"
android:textColor="#color/white"
android:layout_gravity="center_horizontal"
android:gravity="center" />
</LinearLayout>
<Button
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:layout_marginTop="20dp"
android:background="#123456"
android:layout_width="wrap_content"
android:layout_height="35dp"
android:layout_gravity="center"
android:gravity="center"
android:textColor="#ffffff"
android:textSize="14sp"
android:onClick="onUpdateClicked"
android:text="Button" />
Instead of using default alert dialog, make a custom layout something like my layout here. And perform desired action on button.
You can call n show this layout without inflating like this.
EDIT:1
public void showUpdateLayout() {
mParentView = (ViewGroup) findViewById(android.R.id.content);
if (mParentView != null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
mUpdateLayout = inflater.inflate(R.layout.upadte_layout, mParentView, false);
mParentView.addView(mUpdateLayout);
if (mUpdateLayout != null) {
mUpdateLayout.setVisibility(View.VISIBLE);
}
}
Write this method in ur public Class (or Custom Aprent Activity). and call this method when u need to alert.
you should make custom dialog and set it's root view background color to be transparent: android:background="#android:color/transparent"
You will need to create a custom DialogFragment. Below I will give an analytical example of how to implement one and call it with several parameters each time, so you won't need to repeat code each time you want an Dialog with different message.
CustomAlertDialog.java
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
/**
* Custom DialogFragment class
*/
public class CustomAlertDialog extends DialogFragment implements
View.OnClickListener {
/**
* Interface for receiving the wanted callbacks
* */
public interface CallbacksListener
{
public void onPositiveButtonClicked();
public void onNegativeButtonClicked();
}
private CallbacksListener callbacksListener;
public void setCallbacksListener(CallbacksListener callbacksListener)
{
this.callbacksListener = callbacksListener;
}
public CustomAlertDialog()
{
//empty constructor
}
private String titleString;
private String messageString;
private String positiveString;
private String negativeString;
#Override
public void setArguments(Bundle bundle)
{
titleString = bundle.getString("titleString");
messageString = bundle.getString("messageString");
positiveString = bundle.getString("positiveString");
negativeString = bundle.getString("negativeString");
}
public static CustomAlertDialog newInstance(AlertDialogStrings alertDialogStrings)
{
CustomAlertDialog customAlertDialog = new CustomAlertDialog();
Bundle b = new Bundle();
b.putString("titleString", alertDialogStrings.titleString);
b.putString("messageString", alertDialogStrings.messageString);
b.putString("negativeString", alertDialogStrings.negativeString);
b.putString("positiveString", alertDialogStrings.positiveString);
customAlertDialog.setArguments(b);
return customAlertDialog;
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
View v = getActivity().getLayoutInflater().inflate(R.layout.custom_alert_dialog, null);
TextView titleTV = (TextView) v.findViewById(R.id.title_customAlertDialog);
TextView messageTV = (TextView) v.findViewById(R.id.message_customAlertDialog);
Button positiveButton = (Button) v.findViewById(R.id.okBtn_customAlertDialog);
Button negativeButton = (Button) v.findViewById(R.id.cancelBtn_customAlertDialog);
titleTV.setText(titleString);
messageTV.setText(messageString);
positiveButton.setText(positiveString);
negativeButton.setText(negativeString);
positiveButton.setOnClickListener(this);
negativeButton.setOnClickListener(this);
builder.setView(v);
return builder.create();
}
#Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.okBtn_customAlertDialog:
callbacksListener.onPositiveButtonClicked();
dismiss();
break;
case R.id.cancelBtn_customAlertDialog:
callbacksListener.onNegativeButtonClicked();
dismiss();
break;
default:
break;
}
}
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
try
{
callbacksListener = (CallbacksListener) activity;
}
catch (ClassCastException e)
{
throw new ClassCastException(activity.toString()
+ " must implement CallbacksListener");
}
}
#Override
public void onDetach()
{
super.onDetach();
callbacksListener = null;
}
/**
* Class for saving the wanted Strings we want to have on our CustomDialog implementation
* */
public static class AlertDialogStrings
{
public String titleString;
public String messageString;
public String positiveString;
public String negativeString;
public AlertDialogStrings(String title, String message, String positiveString, String negativeString)
{
this.messageString = message;
this.titleString = title;
this.positiveString = positiveString;
this.negativeString = negativeString;
}
}
}
custom_alert_dialog.xml:
<?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="wrap_content"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:textSize="22sp"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:text="My Title Here"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"
android:id="#+id/title_customAlertDialog"/>
<TextView
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="7dp"
android:id="#+id/message_customAlertDialog"
android:layout_below="#id/title_customAlertDialog"
android:textColor="#color/darkGray"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<LinearLayout
style="?android:attr/buttonBarStyle"
android:layout_marginTop="7dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:measureWithLargestChild="true"
android:layout_below="#+id/message_customAlertDialog"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true">
<Button
android:layout_height="wrap_content"
style="?android:attr/buttonBarButtonStyle"
android:textSize="13sp"
android:textColor="#color/primaryColorDark"
android:layout_width="wrap_content"
android:layout_weight="1.0"
android:text="#string/cancel"
android:id="#+id/cancelBtn_customAlertDialog"/>
<Button
android:layout_width="wrap_content"
android:layout_weight="1.0"
android:layout_marginRight="10dp"
android:textSize="13sp"
android:textColor="#color/primaryColorDark"
android:layout_height="wrap_content"
style="?android:attr/buttonBarButtonStyle"
android:text="#string/ok"
android:id="#+id/okBtn_customAlertDialog"/>
</LinearLayout>
To show your customAlertDialog:
private void popUpAlertDialog()
{
String title = "My title here?";
String message = "My Message here";
String positiveString = "OK";
String negativeString = "Cancel";
CustomAlertDialog.AlertDialogStrings customDialogStrings =
new CustomAlertDialog.AlertDialogStrings
(title, message, positiveString, negativeString);
CustomAlertDialog customAlertDialog =
CustomAlertDialog.newInstance(alertDialogStrings);
customAlertDialog.show(getSupportFragmentManager(), "customAlertDialog");
customAlertDialog.setCallbacksListener(new CustomAlertDialog.CallbacksListener()
{
#Override
public void onPositiveButtonClicked()
{
//do something
}
#Override
public void onNegativeButtonClicked()
{
//do something
}
});
}
The AlertDialogStrings class helps us maintain our wanted strings in a way that we can re-use our class with different strings each time and the CallbacksListener helps as settle the way of the OnClick responds each time. Note that this design follows the Material Design Dialog style principles.
Yes.
All you have to do is create a custom dialog layout.
In order to achieve that you would create a LinearLayout with Transparent BG color and inside it you can do whatever is it that you want.
A quick example:
<LinearLayout android:orientation="vertical"
android:layout_width="300"
android:layout_height="500"
android:background="#android:color/transparent">
<LinearLayout android:orientation="vertical"
android:layout_width="270"
android:layout_height="200">
... your content here
</LinearLayout>
<Button android:layout_width="270"
android:layout_height="200"
android:margin_top="10"/>
</LinearLayout>
If you are using a builder to create your Dialog , you would go for this:
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.your_dialog_layout, null))
...otherwise
Dialog newDialog = new Dialog();
newDialog.setContentView(R.layout.your_dialog_layout);
I cant set my ListView dynamically after getting json response from backend.
SherlockNavigationDrawer extends ActionBarActivity
Activity -
public class Forum extends SherlockNavigationDrawer implements OnClickListener {
AsyncTask<Void, String, Void> forumTask;
ProgressDialog pDialog;
TextView newPost;
Button first, last, next, prev;
ListView list;
LinearLayout nopost;
MyPostListAdapter adapter;
public static final String MyPREFERENCES = "MyPrefs";
SharedPreferences sharedpreferences;
String get = "";
JSONObject json;
JSONParser jp;
JSONArray id, user_id, user_name, date, file_path, description, title,
hut_name, hut_id, ttl_likes, ttl_comment;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.forum);
setTitle("Space Huts | Forum");
// newPost = (TextView) findViewById(R.id.tv_test);
first = (Button) findViewById(R.id.bt_first);
prev = (Button) findViewById(R.id.bt_prev);
next = (Button) findViewById(R.id.bt_next);
last = (Button) findViewById(R.id.bt_last);
list = (ListView) findViewById(R.id.lv_posts);
nopost = (LinearLayout) findViewById(R.id.ll_none);
first.setOnClickListener(this);
prev.setOnClickListener(this);
next.setOnClickListener(this);
last.setOnClickListener(this);
// do a get request to server for getting latest 5 pagination posts
doGETrqst("first");
}
private void doGETrqst(final String page) {
// TODO Auto-generated method stub
forumTask = new AsyncTask<Void, String, Void>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Forum.this);
pDialog.setMessage("Refreshing " + page + " page.....");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
sharedpreferences = getSharedPreferences(MyPREFERENCES,
Context.MODE_PRIVATE);
String usrid = sharedpreferences.getString("sesid", "");
// Create URL string
String URL = "http://xxx.xxx?id="
+ usrid + "&page=" + page;
Log.i("json url ", URL);
try {
jp = new JSONParser();
JSONObject json = jp.getJSONFromUrl(URL);
id = json.getJSONArray("id");
user_id = json.getJSONArray("user_id");
user_name = json.getJSONArray("user_name");
date = json.getJSONArray("date");
file_path = json.getJSONArray("file_path");
description = json.getJSONArray("description");
title = json.getJSONArray("title");
hut_name = json.getJSONArray("hut_name");
hut_id = json.getJSONArray("hut_id");
ttl_likes = json.getJSONArray("ttl_likes");
ttl_comment = json.getJSONArray("ttl_comment");
Log.e("recieved" , id.getString(2));
} catch (Exception ex) {
Log.e("error","error");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
forumTask = null;
pDialog.dismiss();
setListView();
}
};
forumTask.execute(null, null, null);
}
private void setListView() {
// TODO Auto-generated method stub
final List<Posts> listposts = new ArrayList<Posts>();
// create list view arraylist for list adapter
for (int i = 0, length = title.length(); i < length - 1; ++i) {
Posts post = new Posts();
try {
post.setHutname(hut_name.getString(i));
post.setPostname(title.getString(i));
post.setUsername(user_name.getString(i));
post.setDate(date.getString(i));
listposts.add(post);
} catch (JSONException e) {
Toast.makeText(this, "Oooppss connectivity error",
Toast.LENGTH_SHORT).show();
}
}
// if there are new posts to show , remove nopost linear layout
if (listposts.size() > 0) {
nopost.setVisibility(View.GONE);
//set the adapter
adapter = new MyPostListAdapter(listposts , Forum.this );
list.setAdapter(adapter);
}
}
#Override
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.bt_first:
doGETrqst("first");
break;
case R.id.bt_next:
doGETrqst("next");
break;
case R.id.bt_prev:
doGETrqst("prev");
break;
case R.id.bt_last:
doGETrqst("last");
break;
}
}
}
I want to fill my list view dynamically by getting json response from backend , when user press buttons to get next or previous posts.
However there are no errors in logcat , neither the list view is shown .But this part of setListView() do works ,as my linearlayout implements View.GONE successfully -
if (listposts.size() > 0) {
nopost.setVisibility(View.GONE);
//set the adapter
adapter = new MyPostListAdapter(listposts , Forum.this );
list.setAdapter(adapter);
}
XML LAYOUT forum.xml -
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
android:orientation="vertical"
android:weightSum="0" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="20"
android:orientation="vertical" >
<TextView
android:id="#+id/tv_newpost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_gravity="center"
android:background="#drawable/general_buttons"
android:clickable="true"
android:text="New Post"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#drawable/click_text_color"
android:textSize="30dp" />
<LinearLayout
android:id="#+id/ll_none"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:background="#drawable/shadow"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="#+id/tv_none"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:fontFamily="sans-serif-thin"
android:text="No New Post"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#000000" />
<ImageView
android:id="#+id/iv_none"
android:layout_width="150dp"
android:layout_height="match_parent"
android:src="#drawable/none" />
</LinearLayout>
<ScrollView
android:id="#+id/sv_posts"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/lv_posts"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:visibility="gone" >
</ListView>
</ScrollView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal" >
<Button
android:id="#+id/bt_first"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:background="#drawable/general_buttons"
android:paddingLeft="15dp"
android:paddingRight="20dp"
android:text="FIRST"
android:textColor="#drawable/click_text_color" />
<Button
android:id="#+id/bt_prev"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/general_buttons"
android:paddingLeft="15dp"
android:paddingRight="20dp"
android:text="<<"
android:textColor="#drawable/click_text_color" />
<Button
android:id="#+id/bt_next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/general_buttons"
android:paddingLeft="20dp"
android:paddingRight="15dp"
android:text=">>"
android:textColor="#drawable/click_text_color" >
</Button>
<Button
android:id="#+id/bt_last"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:background="#drawable/general_buttons"
android:paddingLeft="20dp"
android:paddingRight="15dp"
android:text="LAST"
android:textColor="#drawable/click_text_color" />
</LinearLayout>
</LinearLayout>
After getting responses i updated my code like this -
in onCreate() - before doGETReqst() -
adapter = new MyPostListAdapter(listResults , Forum.this );
list.setAdapter(adapter);
in setListView() -
if (listposts.size() > 0) {
nopost.setVisibility(View.GONE);
//set the adapter
listResults.clear();
listResults.addAll(listposts);
adapter.notifyDataSetChanged();
}
My result is this, now how can i set this into scrollview, in which i nested ListView...i checked my all layouts -
Finally after removing android:view="gone" , adding adapter.notifyDataSetChanged(); and removing scrollview above listview i was able to get this -
Thank you guyz
Your adapter should be created with a List object (for example listResults) and in the setListView do something like:
if (listposts.size() > 0) {
nopost.setVisibility(View.GONE);
//clear old results
listResults.clear();
//load all results
listResults.addAll(listposts);
//notify the adapter about the changes
adapter.notifyDataSetChanged();
}
The point is... create an adapter over an list so... you have ONE instance of that list.
Then update the contents of that list (don't create a new instance), and tell the adapter that the collection has changed.
Try it and let mw know if it works.
In your layout you have android:visibility="gone" set for your listview. I don't see that being toggled in your code.
The answer about updating the adapter instead of creating a new instance is also correct. Initialize your adapter along with your listview and set it (using setAdapter) in the initialization phase. Then when your new data comes in (I modified the code given in the other answer as it was confusing - what's listResults?):
adapter.clear();
//load all results
adapter.addAll(listposts);
//notify the adapter about the changes
adapter.notifyDataSetChanged();
What I am trying to do is to have a simple sms application. The user puts their name and number in, and chooses to toggle a boolean box, and the enter button creates an intent to open up the built in sms and create a message according to the inputs.
What I'm having issues with is resetting the forms when I bring the application up again. Idealy I would like to have the entire application RESTART if you will, but Im not too sure how that works.
I was told to use:
editText.setText("");
to bring the fields to be null again, but eclipse isn't kind to me.
So my question is, how do I change my main_activity file with the code above to clear the edit text forms upon button press.
public class MainActivity extends Activity {
public boolean sexybox = false;
public void sexyBoolean(View view){ // changes the value from true to false etc
if(sexybox == false)
{
sexybox = true;
}
else
{
sexybox = false;
}
}
/** Called when the user clicks the Send button */
public void sendText(View view) {
Intent smsIntent = new Intent(Intent.ACTION_VIEW);
//gives me user and number to be used.
EditText username = (EditText) findViewById(R.id.edit_name);
EditText usernumber = (EditText) findViewById(R.id.edit_number);
String usernamestring = username.getText().toString();
String usernumberstring = usernumber.getText().toString();
//checks if its null fields:
if(usernamestring.isEmpty())
{
Context context = getApplicationContext();
CharSequence text = "What's your name?";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
TextView v = (TextView) toast.getView().findViewById(android.R.id.message);
v.setTextColor(Color.CYAN);
toast.show();
return;
}
if(usernumberstring.isEmpty())
{
Context context = getApplicationContext();
CharSequence text = "What's your numbah?";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
TextView v = (TextView) toast.getView().findViewById(android.R.id.message);
v.setTextColor(Color.CYAN);
toast.show();
return;
}
///
System.out.println("SENDING MESSAGE:");
System.out.println(usernamestring);
System.out.println(usernumberstring);
String body = "Hi Jake - I'm " + usernamestring + "! I'm sending a self text so we can talk or whatever. ";
//IF CUTE button toggled
if(sexybox == true)
{
body = body + "I think you're hot too ;)";
}
smsIntent.putExtra("sms_body", body); //obvi the message
smsIntent.putExtra("address", usernumberstring); //obvi the number, replace usernumberstring
smsIntent.setType("vnd.android-dir/mms-sms"); // guess i leave this alone
//RESET FIELDS ????
// EditText edit_name = (EditText) findViewById(R.id.edit_name);
// edit_name.setText("");
// editText.setText("");
//editText.setText(null);
startActivity(smsIntent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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;
}
}
// XML:
<TextView
android:id="#+id/toptext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#303030"
android:text="#string/toptext"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#33B5E5"
android:textSize="50sp" />
<TextView
android:id="#+id/toptext2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#303030"
android:text="#string/toptext2"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#33B5E5" />
<EditText
android:id="#+id/edit_name"
android:layout_width="match_parent"
android:layout_height="75dp"
android:ems="10"
android:hint="#string/edit_name" />
<EditText
android:id="#+id/edit_number"
android:layout_width="match_parent"
android:layout_height="137dp"
android:ems="10"
android:hint="#string/edit_number"
android:inputType="phone" />
<TextView
android:id="#+id/thanks"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:text="#string/thanks"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#33B5E5" />
<CheckBox
android:id="#+id/sexycheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="sexyBoolean"
android:text="#string/sexycheckbox" />
<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#303030"
android:onClick="sendText"
android:text="#string/button_send"
android:textColor="#android:color/white" />
</LinearLayout>
building android,location based application. I have my class that initiate google maps api work (MygoogleMapsActivator). this is constractor of this class
public MyGoogleMapsActivator(Context mContext)
{
this.mContext = mContext;
}
.
Context mContext is a activity where i need to display map and address,a pass it here for getting services that i need to activate.Activity displaying the results - my location and address(location and address i am getting from MyGoogleMapsActivator)
when i want to display it on my activity i get this exception in LogCat: Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
i am getting ti from this function:
public void SetUpTextViewWithAddress()
{
text = (TextView) findViewById(R.id.address);
text.append(addressString);
setContentView(text);
}
How can i solved it,thanks.
This is full code of my activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_new_place);
mGoogleMapsActivator = new MyGoogleMapsActivator(this);
Button buttonAddPlace = (Button) findViewById(R.id.buttonAddPlace);
Button buttonAddByAddress = (Button) findViewById(R.id.buttonAddByAddress);
fm = (SupportMapFragment ) getSupportFragmentManager().findFragmentById(R.id.map);
buttonAddPlace.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AddNewPlaceActivity.this, AddByAddress.class);
mMyPlace = new Places("", city, street, number, "", LoggedWithFacebookMainActivity.GetLoggedInUserName(), myPosition.latitude, myPosition.longitude);
intent.putExtra("Place", mMyPlace);
//intent.putExtra("TheStreet", street);
//intent.putExtra("TheNumber", number);
intent.putExtra("Clarification");
startActivity(intent);
}
});
buttonAddByAddress.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(AddNewPlaceActivity.this, AddByAddress.class);
mMyPlace = new Places("", city, street, number, "", LoggedWithFacebookMainActivity.GetLoggedInUserName(), myPosition.latitude, myPosition.longitude);
intent.putExtra("Place", mMyPlace);
// intent.putExtra("TheStreet", "Street");
// intent.putExtra("TheNumber", "Number");
intent.putExtra("Clarification");
startActivity(intent);
}
});
mGoogleMapsActivator.SetUpMapIfNeed(fm);
mGoogleMapsActivator.SetMyGoggleActivatorLocationEnabled();
mGoogleMapsActivator.SetUpService();
mGoogleMapsActivator.setUpListener();
mGoogleMapsActivator.SetUpAndGetProvider();
mGoogleMapsActivator.SetMyLocationWithListener();
mGoogleMapsActivator.SetMyPosition();
mGoogleMapsActivator.SetUpMyMarker();
mGoogleMapsActivator.SetUpMapView();
mGoogleMapsActivator.SetUpAddressFromGeocoder();
city = mGoogleMapsActivator.getCity();
street = mGoogleMapsActivator.getStreet();
number = mGoogleMapsActivator.getNumber();
addressString = mGoogleMapsActivator.getAddressString();
SetUpTextViewWithAddress();
mGoogleMapsActivator.AnimateCamera();
public void SetUpTextViewWithAddress()
{
text = (TextView) findViewById(R.id.address);
text.setText(addressString);
// setContentView(text);
}
}
XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="end"
tools:context=".AddNewPlaceActivity" >
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="370dp" />
<TextView
android:id="#+id/address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/buttonAddByAddress"
android:layout_alignParentLeft="true"
android:layout_below="#+id/map"
android:layout_toLeftOf="#+id/buttonAddPlace"
android:text="#string/place_address_he" />
<Button
android:id="#+id/buttonAddPlace"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/buttonAddByAddress"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/address"
android:background="#drawable/custom_button_main"
android:paddingBottom="10dp"
android:text="#string/add_place_he" />
<Button
android:id="#+id/buttonAddByAddress"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:background="#drawable/custom_button_main"
android:paddingTop="10dp"
android:text="#string/add_place_manually_he" />
</RelativeLayout>
Thanks
The issue is the TextView is already attached to your view hierarchy. I'm guessing the view with address id is already inside the main layout file you are using for your activity, without the full activity code it's hard to tell. If this is true you should remove the setContentView call as it isn't needed. Make sure you want to append the text to what may already be in the TextView, if you want to replace the text you should use setText instead of append.