how to request an url with an edittext - java

i need to find a way to request an url with an edit text and display the json of that url. i have tried to use this code :
// URL to get contacts JSON
private static String id = null;
private static String url = "http://api.ccapp.it/v1/student/" + id + "/schedule/11";
// JSON Node names
private static final String TAG_LESSON = "class";
private static final String TAG_ROOM = "room";
private static final String TAG_TEACHER = "teacher";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.roosteralluz);
//number input
final EditText input = (EditText) findViewById(R.id.editText2);
//search button
Button btnSearch = (Button) findViewById(R.id.button34);
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
id = input.getText().toString();
// Calling async task to get json
new GetContacts().execute();
}
});
But when i try that code it returns this error: org.json.JSONException: Value <html><head><title>Slim of type java.lang.String cannot be converted to JSONObject
It is able to parse a link if i change id (look at code) to my own id. but i need to find a user his own id with an edittext.

Instead of using JsonArray, try Gson library to convert from Json to String and vice versa.

Related

Edit values and update in firebase

this time i want to edit and update the new values in Firebase Database. I have read the firebase documentation and followed the steps. https://firebase.google.com/docs/database/android/read-and-write#update_specific_fields
i need a litte orientation, following the documentation's steps i have modifed my POJO class,
as proof just add the interno key in the public Map<>...
public class Cow implements Serializable {
String interno;
public Cow() {
}
public Cow(String interno) {
this.interno = interno;
}
public String getInterno() {
return interno;
}
public void setInterno(String interno) {
this.interno = interno;
}
#Exclude
public Map<String, Object> toMap() {
HashMap<String, Object> result = new HashMap<>();
result.put("inte", interno);
return result;
}
}
This is my database in firebase
I have a recyclerview and I send the values to another activity by an intent, where i show the details, in this detailcow i want to modify the values.
This is the code:
public class Cowdetail extends AppCompatActivity {
DatabaseReference reference;
EditText tvinterno, tvsiniiga, tvpadre, tvmadre, tvnacimiento, tvinseminacion, tvtoro, tvestatus, tvnotas;
AppCompatImageView tvimage;
Button tvbutton;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detailcow);
tvinterno = (EditText) findViewById(R.id.tvinterno);
tvsiniiga = (EditText) findViewById(R.id.tvsiniiga);
tvpadre = (EditText) findViewById(R.id.tvpadre);
tvmadre = (EditText) findViewById(R.id.tvmadre);
tvnacimiento = (EditText) findViewById(R.id.tvnacimiento);
tvinseminacion = (EditText) findViewById(R.id.tvinsemincion);
tvtoro = (EditText) findViewById(R.id.tvtoro);
tvestatus = (EditText) findViewById(R.id.tvestatus);
tvnotas = (EditText) findViewById(R.id.tvnotas);
tvimage = (AppCompatImageView) findViewById(R.id.tvimage);
tvbutton = findViewById(R.id.actualizar);
String vpadre = "";
String vmadre = "";
String vinterno = "";
String vsiniiga = "";
String vnacimiento = "";
String vinseminacion = "";
String vtoro = "";
String vestatus = "";
String vnotas = "";
String vurl;
Bundle extras = getIntent().getExtras();
if (extras !=null);
vinterno = extras.getString("keyint");
vsiniiga = extras.getString("keysin");
vmadre = extras.getString("madre");
vpadre = extras.getString("padre");
vnacimiento = extras.getString("nacimiento");
vinseminacion = extras.getString("inseminacion");
vtoro = extras.getString("toro");
vestatus = extras.getString("estatus");
vnotas = extras.getString("notas");
String image = extras.getString("img");
if (image == null|| image.isEmpty()){
tvimage.setImageResource(R.drawable.ic_imageinf);
} else {
Picasso.get().load(image).fit().centerCrop().into(tvimage);
}
tvpadre.setText(vpadre);
tvinterno.setText(vinterno);
tvsiniiga.setText(vsiniiga);
tvmadre.setText(vmadre);
tvnacimiento.setText(vnacimiento);
tvinseminacion.setText(vinseminacion);
tvtoro.setText(vtoro);
tvestatus.setText(vestatus);
tvnotas.setText(vnotas);
tvbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Update();
}
});
}
private void Update() {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Vacas");
Map<String, Object> updates = new HashMap<String, Object>();
updates.put("inte", tvinterno);
ref.updateChildren(updates);
}
}
I have added a button to the layout, it has to save the edited values to firebase with the public void Update, Im doing something wrong, but in my short (almost nil) experience i can't see the error. also, i'm looking for a asesor who can guide me in my project, if someone want to talk about it, send me an email to: pjcm97#outlook.com
Firebase Realtime Database stores JSON data. You're trying to write an EditText object to it, which is not JSON data. So your code is most likely crashing.
private void Update() {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Vacas");
Map<String, Object> updates = new HashMap<String, Object>();
updates.put("inte", tvinterno.getText().toString());
ref.updateChildren(updates);
}
I also highly recommend always checking the result of a write operation, to see if it succeeded, as shown in the documentation on adding a completion listener.

Android Volley String Request not sending POST Data to user database

I am writing an android app to interact with a user database on a live server. I'm currently working on a 'register user' activity, which is supposed to simply add a user to the database, based on information they enter in an edit text field.
I am Using Android's Volley Library to accomplish this, using a simple String Request. The request is then added to a request queue. I am able to connect and get a response from the server, but when I attempt to update the database (add a user) nothing happens.
I understand that while using method=POST (which my server does), one must override the getParams() method specifying Key/Value pairs (where KEY is the post data from the php script and the value is the new data.)
Ive tried implementing my request queue as a singleton class, creating a custom header, and even tried modifying volley's method from POST to 'DEPRECATED_GET_OR_POST' with no luck. If someone can tell me what i'm doing wrong or what's missing id greatly appreciate it.
Here's my code:
//url to the registration page (on the server)
private static final String Register_URL = "http://www.wupx.com/arcums/profile/register.php";
//key values (these are the values in the DB)
public static final String Key_Username = "username";
public static final String Key_Realname = "name";
public static final String Key_Password = "password2";
public static final String Key_Email = "email";
//declare the editText field & Button
private EditText editTextUsername;
private EditText editTextName;
private EditText editTextEmail;
private EditText editTextPassword;
private EditText editTextPassword2;
private Button buttonRegister;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
//reference editText fields and buttons
editTextUsername = (EditText) findViewById(R.id.editTextUserName);
editTextName = (EditText) findViewById(R.id.editTextRealName);
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
editTextPassword2 = (EditText) findViewById(R.id.editTextPasswordAgain);
buttonRegister = (Button) findViewById(R.id.registerButton);
buttonRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
registerUser();//calls the registerUser method.
}
});
}
//method to add user to the arcums database
private void registerUser() {
//print textview contents to logcat (debugging)
Log.d("log message", "entering register User method");
//values passed in from the user
final String Username = editTextUsername.getText().toString().trim();
final String Name = editTextName.getText().toString().trim();
final String Password = editTextPassword.getText().toString().trim();
final String Password2 = editTextPassword2.getText().toString().trim();
final String Email = editTextEmail.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, Register_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// put a toast here
Toast.makeText(register.this, R.string.register_response , Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error toast
Toast.makeText(register.this, R.string.register_error, Toast.LENGTH_SHORT).show();
}
}){
//returns a hashmap with key value pairs
#Override
protected Map<String,String> getParams(){
Map<String, String> params = new HashMap<String, String>();
params.put(Key_Username, Username);
params.put(Key_Realname, Name);
params.put(Key_Password, Password2);
params.put(Key_Email, Email);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
and here's a screenshot of my DB values in php myadmin:
DB values
note that not all fields need to be filled out in order to be added to the database- just name, username, email, and password.
the server itself has no GUI so i'm unable to post the PHP code at the moment. I hope someone can help with the information given!

Android - App crashes when button is clicked to show an activity with listview

I have this code found around the net and decided to try it on my app if it's applicable. When the button is clicked it should show an activity when all the data from the database are being shown in the list view.
Here's the code:
MainActivity.java
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://api.androidhive.info/contacts/";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main5);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity5.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone node is JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_EMAIL, email);
contact.put(TAG_PHONE_MOBILE, mobile);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity5.this, contactList,
R.layout.list_item, new String[] { TAG_NAME, TAG_EMAIL,
TAG_PHONE_MOBILE }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}
}
Then here's the class where the button is located:
public class MainActivity3Activity extends Activity implements OnClickListener {
Button ViewGradesActivity;
Button ClassScheduleActivity;
Button CalendarOfActivitiesActivity;
Button AccountBalanceActivity;
Button StudentProfileActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity3);
ShowMainActivity= (Button) findViewById(R.id.mainactbutton);
ShowMainActivity.setOnClickListener(this);
ClassScheduleActivity = (Button) findViewById(R.id.classSched);
ClassScheduleActivity.setOnClickListener(this);
CalendarOfActivitiesActivity = (Button) findViewById(R.id.activities);
CalendarOfActivitiesActivity.setOnClickListener(this);
AccountBalanceActivity = (Button) findViewById(R.id.balance);
AccountBalanceActivity.setOnClickListener(this);
StudentProfileActivity = (Button) findViewById(R.id.profile);
StudentProfileActivity.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch(view.getId()) {
//this is to show the activity with the list view
case R.id.mainactbutton:
startActivity(new Intent(this,MainActivity5.class));
break;
case R.id.classSched:
startActivity(new Intent(this,classSchedule.class));
break;
case R.id.activities:
startActivity(new Intent(this,CalendarOfActivities.class));
break;
case R.id.balance:
startActivity(new Intent(this,AccountBalance.class));
break;
case R.id.profile:
startActivity(new Intent(this,StudentProfile.class));
break;
}
}
}
So whenever I click that mainactbutton the app crashes. What should I do? Is there something wrong with the activity with the list view?
Thank you for the help.
EDIT: Now that I have edited the manifest file and added the MainActivity5 the app still crashed and here's the log:
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
at android.app.ListActivity.onContentChanged(ListActivity.java:243)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:277)
at android.app.Activity.setContentView(Activity.java:1881)
at com.example.kreshiathea.myfirstapp.MainActivity5.onCreate(MainActivity5.java:52)
at android.app.Activity.performCreate(Activity.java:5122)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
Here is my list view:
activity_main5.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<!-- Main ListView
Always give id value as list(#android:id/list)
-->
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
            
have you declared this activity in your AndroidManifest.xml?
Every activity you use have to be declared in your manifest
<activity
android:name="com.example.kreshiathea.myfirstapp.MainActivity5"
android:label="#string/app_name"
android:id="#android:id/list"
>
</activity>
You must declare MainActivity5 class in AdnroidManifest.xml file
If you extends from ListActivity, then don't use setContentView(). You need get the default list view get by getListView().
Listview listview=getListView();
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Change your code to
this.startActivity(new Intent(this,MainActivity5.class));
& have you declared this activity in your AndroidManifest.xml?

Put JSON array data in Hashmap and pass it through Intent Extra

In my app, I have successfully implemented passing JSON Objects via Intent to a new activity by doing find "findviewByid."
Now this is a restaurant finder app, and each restaurant has several menu photos. I was looking all over stackoverflow to find sth like it but couldn't implement.
This is a part of my JSON file:
[
{
login_id: "6",
name: "Urban Spice",
location: "banani",
latitude: "23.790327",
longitude: "90.409007",
address: "House- 119, Road-11, Block-E, Banani",
rating: "4.00",
costfortwopeople: "0",
openingclosingtime: "",
type: "restaurant,ice cream parlour",
perks: "kids zone,home delivery,catering",
cuisine: "indian,indonesian",
phone: "01777899901,2,3,9862672",
image: - [
"http://www.petuuk.com/restaurant_images/img_2146.jpg",
"http://www.petuuk.com/restaurant_images/img_2147.jpg"
],
menu: - [
"http://www.petuuk.com/restaurant_images/.jpg",
"http://www.petuuk.com/restaurant_images/.jpg",
"http://www.petuuk.com/restaurant_images/.jpg",
"http://www.petuuk.com/restaurant_images/.jpg",
"http://www.petuuk.com/restaurant_images/.jpg",
"http://www.petuuk.com/restaurant_images/.jpg",
"http://www.petuuk.com/restaurant_images/.jpg",
"http://www.petuuk.com/restaurant_images/.jpg"
]
},
{
login_id: "7",
name: "The Sky Room Dining",
location: "banani",
latitude: "23.793972",
longitude: "90.403190",
address: "ABC House, 12th Floor, 8 Kemal Ataturk Avenue, Banani",
rating: "4.00",
costfortwopeople: "0",
openingclosingtime: "",
type: "restaurant",
perks: "rooftop view,catering",
cuisine: "thai,indian",
phone: "01675019211,9822017",
image: - [
"http://www.petuuk.com/restaurant_images/img_2204.jpg",
"http://www.petuuk.com/restaurant_images/img_2205.jpg",
"http://www.petuuk.com/restaurant_images/img_2206.jpg"
], etc..................................................................
I'm having a hard time retrieving the JSON array "menu" and "image" from the JSON output as above. I was able to retrieve the other JSON Objects such as login_id, name, location etc.
The main objective I am trying to achieve here is, load all the data in the Listview, where a user can search a restaurant, then when the user clicks on the specific restaurant, all the loaded data should gets into the "Intent.putExtra" for getting viewed in a full restaurant profile view in a new activity.
These are parts of my "SeachAll" activity where I need help. This is the for loop for retrieving data from the JSON file. I need help here retrieving data from "image" and "menu" and then putting it into my hashmap.
protected String doInBackground(String... arg) {
//building parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
//Getting JSON from URL
String json = jsonParser.makeHttpRequest(URL_RESTAURANT_LIST, "GET", params);
//Log Cat Response Check
Log.d("Areas JSON: ", "> " + json);
try {
restaurants = new JSONArray(json);
if (restaurants != null) {
//loop through all restaurants
for (int i = 0; i < restaurants.length(); i++) {
JSONObject c = restaurants.getJSONObject(i);
//Storing each json object in the variable.
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String location = c.getString(TAG_LOCATION);
String rating = c.getString(TAG_RATING);` HashMap<String, String> map = new HashMap<String, String>();
//adding each child node to Hashmap key
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_LOCATION, location);
map.put(TAG_RATING, rating);
//adding HashList to ArrayList
restaurant_list.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}`
This is my onItemClick. Need help in putting the arrays, I dont know if it is alright to pass json array just like json objects i did below.
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(), RestaurantProfile.class);
String loginId = ((TextView) view.
findViewById(R.id.login_id)).
getText().toString();
String res_name = ((TextView) view.
findViewById(R.id.restaurant_name)).
getText().toString();
intent.putExtra(TAG_ID, loginId);
intent.putExtra(TAG_NAME, res_name);
startActivity(intent);
}
});
So In brief I need help with two things,
1. Retrieve JSON array "image" and "menu" URLS from the JSON file and put it inside the Hashmap.
2. Put this data to my Intent for being passed to a new activity.
This my full code for "SearchAll" activity.
public class SearchAll extends ListActivity {
ConnectionDetector cd;
AlertDialogManager alert = new AlertDialogManager();
//Progress Dialog
private ProgressDialog pDialog;
//make json parser Object
JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> restaurant_list;
//Restaurant Json array
JSONArray restaurants = null;
private static final String URL_RESTAURANT_LIST
= "http://www.petuuk.com/android/allRestaurantList2.php";
//all JSON Node Names
private static final String TAG_ID = "login_id";
private static final String TAG_NAME = "name";
private static final String TAG_LOCATION = "location";
private static final String TAG_LAT = "lattitude";
private static final String TAG_LONG = "longitude";
private static final String TAG_ADDRESS = "address";
private static final String TAG_COST_2 = "costfortwopeople";
private static final String TAG_TYPE = "type";
private static final String TAG_PERKS = "perks";
private static final String TAG_CUISINE = "cuisne";
private static final String TAG_PHONE = "phone";
private static final String TAG_RATING = "rating";
private static final String TAG_IMAGE = "image";
private static final String TAG_MENU = "menu";
private static final String TAG_TIMING = "openingclosingtime";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_all);
cd = new ConnectionDetector(getApplicationContext());
//Check for Internet Connection
if (!cd.isConnectingToInternet()) {
//Internet connection not present
alert.showAlertDialog(SearchAll.this, "Internet Connection Error",
"Please Check Your Internet Connection", false);
//stop executing code by return
return;
}
restaurant_list = new ArrayList<HashMap<String, String>>();
//get ListView
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(), RestaurantProfile.class);
String loginId = ((TextView) view.
findViewById(R.id.login_id)).
getText().toString();
String res_name = ((TextView) view.
findViewById(R.id.restaurant_name)).
getText().toString();
intent.putExtra(TAG_ID, loginId);
intent.putExtra(TAG_NAME, res_name);
startActivity(intent);
}
});
lv.setOnScrollListener(new EndlessScrollListener() {
#Override
public void onLoadMore(int page, int totalItemsCount) {
}
});
new LoadRestaurants().execute();
}
class LoadRestaurants extends AsyncTask<String, String, String> {
//Show Progress Dialog
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SearchAll.this);
pDialog.setMessage("Loading All Restaurants...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... arg) {
//building parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
//Getting JSON from URL
String json = jsonParser.makeHttpRequest(URL_RESTAURANT_LIST, "GET", params);
//Log Cat Response Check
Log.d("Areas JSON: ", "> " + json);
try {
restaurants = new JSONArray(json);
if (restaurants != null) {
//loop through all restaurants
for (int i = 0; i < restaurants.length(); i++) {
JSONObject c = restaurants.getJSONObject(i);
//Storing each json object in the variable.
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String location = c.getString(TAG_LOCATION);
String rating = c.getString(TAG_RATING);
String address = c.getString(TAG_ADDRESS);
String latitude = c.getString(TAG_LAT);
String longitude = c.getString(TAG_LONG);
String costfor2 = c.getString(TAG_COST_2);
String timing = c.getString(TAG_TIMING);
String type = c.getString(TAG_TYPE);
String perks = c.getString(TAG_PERKS);
String cuisine = c.getString(TAG_CUISINE);
String phone = c.getString(TAG_PHONE);
JSONArray menuArray = c.getJSONArray("menu");
JSONArray imagesArray = c.getJSONArray("image");
//Creating New Hashmap
HashMap<String, String> map = new HashMap<String, String>();
//adding each child node to Hashmap key
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_LOCATION, location);
map.put(TAG_RATING, rating);
for(int m=0;m<menuArray.length();++m){
map.put("MENU_" + m,menuArray.getString(m));
}//menu for loop
map.put("TOTAL_MENU", menuArray.length());
// map.put(TAG_MENU, String.valueOf(menu));
//adding HashList to ArrayList
restaurant_list.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
//dismiss the dialog
pDialog.dismiss();
//Updating UI from the Background Thread
runOnUiThread(new Runnable() {
#Override
public void run() {
ListAdapter adapter = new SimpleAdapter(
SearchAll.this, restaurant_list,
R.layout.listview_restaurants, new String[]{
TAG_ID, TAG_NAME, TAG_LOCATION, TAG_RATING}, new int[]{
R.id.login_id, R.id.restaurant_name, R.id.location, R.id.rating});
setListAdapter(adapter);
}
});
}
}
}
In short, you don't pass all of your data from one Activity to another. You should just pass a restaurant ID to a new Activity, and it uses that ID to pull data of the restaurant.
You should consider your restaurant list as (part of) Model in an MVC architecture. It should be separated from your Activities (which are Controller). Model is your data expert, it keeps your data in memory, files or a database, and it lives beyound the life-cycle of any particular Activity. You don't pass the Model from one Activity to another. After an Activity is created, it grabs the Model (if the Model is a Singleton) or the Model is injected into that Activity (Dependency Injection, my prefer framework is Dagger). The Activity then can ask for any particular data from the Model and render its View. It can also observe for any further changes within the Model and update its view accordlingly.
not sure of this is exactly what you need, but you might get some ideas out of this
first, to get the image and menu array, from the restaurant, you need this
inside the for loop, where you get the json object (c)
JSONObject c = restaurants.getJSONObject(i);
JsonArray menuArray = c.getJsonArray("menu");
JsonArray imagesArray = c.getJsonArray("image");
and you can loop among menuArray and imagesArray items using a for loop
imagesArray.getString(index);
now, as you have declared your map as < String, String > you can't assign a multiple values (images or menu items) in one string,
so either you find another way to structure your data,
or create another 2 maps, menuPam, imageMap that will have restaurant ID as key, and String as value for menu and image entries.
inside the for loop that read restaurant objects:
for (int i = 0; i < restaurants.length(); i++) {
:
:
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
:
:
JsonArray menuArray = c.getJsonArray("menu");
for(int m=0;m<menuArray.length();++m){
menuMap.add(id,menuArray.getString(m));
}//menu for loop
//another for loop for imageArray...
}//end of restaurants loop
but then you have to add the menuMap and imageMap to an array list, called menus, images...
why don't you create an object to hold all info about restaurant
class restaurant{
private String name="", id =""....
//setters and getters ...
String menuItems[] = null;
String imageItems[] = null;
//setters getters for the arrays.
}
}
EDIT:
this sol does not need a new maps, just add images and menu to same map
using dynamic key name
for(int m=0;m<menuArray.length();++m){
map.add("MENU_" + m,menuArray.getString(m));
}//menu for loop
map.add("TOTAL_MENU", Integer.toString(menuArray.length()));
you can use above code, to add menu items to the map
and same thing to images, "IMAGE_"+m
and TOTAL_IMAGES
now at target activity, read all IMAGE_n and MENU_n in a loop
from 0 to TOTAL_IMAGES, and TOTAL_MENU

String not accessible in same class

I have code to show a toast:
public void checkchallenge(View v) {
String algo = null;
if(algo == "123")
{
Context context = getApplicationContext();
CharSequence text = "You have " + messages ;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
...
the error in eclipse that I am getting is:
messages cannot be resolved to a variable
The variable "messages" is being called in some code above it:
String messages = c.getString(TAG_MESSAGES);
final TextView messages1 = (TextView)findViewById(R.id.envelope);
Maybe it's because I don't know Java too well but why isn't my string variable "messages" or "messages1" getting recognized in my code? I have a feeling it has to do with permissions of the code but when I remove the "final" part off of the messages 1 TextView I get the same error.
Confused!
Here is the entire code to the class:
public class Homepage extends Activity {
//URL to get JSON Arrays
public static String url = "http://10.0.2.2/android/SQL.php?username='";
public static String usernamefromlogin;
public static TextView errorchecking;
//JSON Node Names
private static final String TAG_USER = "users";
private static final String TAG_WINS = "wins";
private static final String TAG_MESSAGES = "messages";
private static final String TAG_NAME = "fullname";
private static final String TAG_DISPLAY = "displayname";
private static final String TAG_EMAIL = "email";
private static final String TAG_PW = "password";
private static final String TAG_CREATED = "created_at";
private static final String TAG_UPDATED = "updated_at";
JSONArray user = null;
//disable back button
#Override
public void onBackPressed() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reshomepage);
//Get login name from EditText in login screen and concatenate it to PHP user-name for _GET command in 3 steps.
//Step 1: Get intent from previous activity
Intent intent = getIntent();
getIntent().getExtras();
//Step 2: convert intent (intent) to string called "usernamefromlogin" //error checking in log cat to see value of "usernamefromlogin"
usernamefromlogin = intent.getExtras().getString("username2"); Log.d("log of usernamefromlogin", usernamefromlogin);
//Step 3: take the string "url" and add string "usernamefromlogin" after it
String url5 = url.concat(usernamefromlogin);
String url6 = url5.concat("'");
//find TextView "errorchecking" and send the string "url6" to it so it can display in log cat
Log.d("log of URL6 in it's final state", url6);
// Creating new JSON Parser
JSONParser jParser = new JSONParser();
// Getting JSON from URL from the final string "url6"
JSONObject json = jParser.getJSONFromUrl(url6);
//Logcat check value for TAG_USER
try {
// Getting JSON Array
user = json.getJSONArray(TAG_USER);
JSONObject c = user.getJSONObject(0);
// Storing JSON item in a String Variable
String name = c.getString(TAG_NAME);
String messages = c.getString(TAG_MESSAGES);
String wins = c.getString(TAG_WINS);
String display = c.getString(TAG_DISPLAY);
String email = c.getString(TAG_EMAIL);
String pw = c.getString(TAG_PW);
String created = c.getString(TAG_CREATED);
String updated = c.getString(TAG_UPDATED);
//Importing TextView
final TextView name1 = (TextView)findViewById(R.id.tvfullname);
TextView messages1 = (TextView)findViewById(R.id.envelope);
final TextView wins1 = (TextView)findViewById(R.id.wins);
final TextView created1 = (TextView)findViewById(R.id.tvcreated_at);
final TextView updated1 = (TextView)findViewById(R.id.tvupdated_at);
//Set JSON Data in its respectable TextView
name1.setText("Hello " + name);
updated1.setText("Your last login was " + updated);
// print error if applicable.
} catch (JSONException e) {
e.printStackTrace();
}
}
public void checkchallenge(View v) {
String algo = null;
if(algo == "123")
{
// display pop up message (toast)
Context context = getApplicationContext();
CharSequence text = "You have " + messages1 ;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}else
{
// display pop up message (toast)
Context context = getApplicationContext();
CharSequence text = "You have no new Challenges";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
}
I suspect the code is making the String messages and TextView local variables inside a method. If you want to access these objects within the entire class they should be declared as fields.
public SomeClass{
String messages;
final TextView messages1;
public void checkchallenge(View v) {
//Method implementation
}
public void someOtherMethod(){
this.messages = c.getString(TAG_MESSAGES);
this.messages1 = (TextView)findViewById(R.id.envelope);
}
}
If your messages variable is defined inside other method it won't be seen at the point you showed.

Categories