XML Parsing giving error - android

I am trying to parse an XML from online on my android project but I get an error. I tried parsing the xml as a basic java project and it works but I don't know how to implement it in my android project. The error on the console says android.os.networkmainthreadException. I did add the permission to App manifest. My code below:
package com.example.medrec;
import java.io.IOException;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
import android.os.Build;
public class Details extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_details);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.details, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_details,
container, false);
//Code to parse starts here
String name[] = null;
String id[] = null;
String type[] = null;
String dosage[] = null;
String remaining[] = null;
DocumentBuilderFactory builderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = null;
try {
builder = builderFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
Document document = null;
String xmlDocument = "http://www2.southeastern.edu/Academics/Faculty/jburris/emr.xml";
try {
document = builder.parse(new URL(xmlDocument).openStream());
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
int total = 0;
// Creates a list of nodes for the root element, emr
NodeList emrRoot = document.getElementsByTagName("emr");
// Gets the first node in the list... really just our root node
Node emrNode = (Node) emrRoot.item(0);
if (emrNode instanceof Element) {
Element emrElement = (Element) emrNode;
// Gets the list of all patient_info nodes
NodeList patInfoList = emrElement
.getElementsByTagName("patient_order");
// Total Number of Records
total = patInfoList.getLength();
System.out.println("Total number of records is: " + total);
name = new String[total];
id = new String[total];
type = new String[total];
dosage = new String[total];
remaining = new String[total];
// Gets the first patient_info node... the first in the list of
// patients
// Fill in the values of our strings. The first is tricky because
// it is an attribute and not the content of the element.
for (int i = 0; i < total; i++) {
Node patInfoNode = (Node) patInfoList.item(i);
if (patInfoNode instanceof Element) {
// Get the element information for parient_info
Element pat_info = (Element) patInfoNode;
// Get the name...
Node n = pat_info.getElementsByTagName("patientName").item(
0);
name[i] = n.getTextContent();
// Get the id...
n = pat_info.getElementsByTagName("patientID").item(0);
id[i] = n.getTextContent();
// Get the type...
n = pat_info.getElementsByTagName("type").item(0);
type[i] = n.getTextContent();
// Get the dosage...
n = pat_info.getElementsByTagName("dosage").item(0);
dosage[i] = n.getTextContent();
// Get the remaining...
n = pat_info.getElementsByTagName("refillsremaining").item(
0);
remaining[i] = n.getTextContent();
}
}
}
//Toast.makeText(getApplicationContext(), type[5], Toast.LENGTH_SHORT).show();
//Code ends here
return rootView;
}
}
}
New Code with asyncTask
package com.example.medrec;
import java.io.IOException;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
import android.os.Build;
public class Details extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_details);
new LongOperation().execute("");
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.details, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String name[] = null;
String id[] = null;
String type[] = null;
String dosage[] = null;
String remaining[] = null;
DocumentBuilderFactory builderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = null;
try {
builder = builderFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
Document document = null;
String xmlDocument = "http://www2.southeastern.edu/Academics/Faculty/jburris/emr.xml";
try {
document = builder.parse(new URL(xmlDocument).openStream());
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
int total = 0;
// Creates a list of nodes for the root element, emr
NodeList emrRoot = document.getElementsByTagName("emr");
// Gets the first node in the list... really just our root node
Node emrNode = (Node) emrRoot.item(0);
if (emrNode instanceof Element) {
Element emrElement = (Element) emrNode;
// Gets the list of all patient_info nodes
NodeList patInfoList = emrElement
.getElementsByTagName("patient_order");
// Total Number of Records
total = patInfoList.getLength();
System.out.println("Total number of records is: " + total);
name = new String[total];
id = new String[total];
type = new String[total];
dosage = new String[total];
remaining = new String[total];
// Gets the first patient_info node... the first in the list of
// patients
// Fill in the values of our strings. The first is tricky because
// it is an attribute and not the content of the element.
for (int i = 0; i < total; i++) {
Node patInfoNode = (Node) patInfoList.item(i);
if (patInfoNode instanceof Element) {
// Get the element information for parient_info
Element pat_info = (Element) patInfoNode;
// Get the name...
Node n = pat_info.getElementsByTagName("patientName").item(
0);
name[i] = n.getTextContent();
// Get the id...
n = pat_info.getElementsByTagName("patientID").item(0);
id[i] = n.getTextContent();
// Get the type...
n = pat_info.getElementsByTagName("type").item(0);
type[i] = n.getTextContent();
// Get the dosage...
n = pat_info.getElementsByTagName("dosage").item(0);
dosage[i] = n.getTextContent();
// Get the remaining...
n = pat_info.getElementsByTagName("refillsremaining").item(
0);
remaining[i] = n.getTextContent();
}
}
}
Toast.makeText(getApplicationContext(), type[5], Toast.LENGTH_SHORT).show();
return null;
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_details,
container, false);
return rootView;
}
}
}

that is a NullPoint error ,I find you may be in the pat_info.getElementsByTagName("refillsremaining"),the "refillsremaining" should be "refillsrRmaining".The r is R.

NetworkOnMainThreadException indicates you are trying to do a long blocking I/O operation on the UI thread. Move your XML download and parsing to its own thread - I recommend AsyncTask to get the job done. AsyncTask will issue a callback to your UI thread when the operation is done.
Example of AsyncTask: AsyncTask Android example
Another example: How to fix android.os.NetworkOnMainThreadException?

Related

Switch data form a context to an activity

I have this class that use a DOMParser to take data from "infofermata.xml". This class is called ReadXMLFile.java:
/**
* Created by Giacomo B on 30/07/2015.
*/
package com.example.giacomob.myapplication;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import static android.support.v4.app.ActivityCompat.startActivity;
import static java.security.AccessController.getContext;
public class ReadXMLFile {
public static void readXMLFile(Context context) {
try {
// Log.i("MyActivity", "casa");
AssetManager assetManager = context.getAssets();
InputStream is = assetManager.open("infofermata.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(is);
// String filePath = "assets/infofermata.xml";
//File fXmlFile = new File(filePath);
//DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
//DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
//Document doc = dBuilder.parse(fXmlFile);
//optional, but recommended
//read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("fermata");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
// Log.i("MyActivity", "casa");
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
// System.out.println("Staff id : " + eElement.getAttribute("id"));
// String stringidfermata = "Id Fermata : " + eElement.getElementsByTagName("idfermata").item(0).getTextContent()"";
// Log.i("MyActivity", "\"Id Fermata : \" + eElement.getElementsByTagName(\"idfermata\").item(0).getTextContent()");
System.out.println("Id Fermata : " + eElement.getElementsByTagName("idfermata").item(0).getTextContent());
String testo1 = eElement.getElementsByTagName("idfermata").item(0).getTextContent();
//I would to switch this string in another activiy
System.out.println(testo1); //provo per vedere se stampa quello che ho messo nella variabile "testo1"
System.out.println("Naziome : " + eElement.getElementsByTagName("nazione").item(0).getTextContent());
System.out.println("Paese : " + eElement.getElementsByTagName("paese").item(0).getTextContent());
System.out.println("Via : " + eElement.getElementsByTagName("via").item(0).getTextContent());
}
is.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I would to switch the string "testo1" in another acrivity called "acivity_page1.xml"
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1">
<TextView
android:layout_width="182dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Ciaoooo"
android:id="#+id/textView2"
android:layout_gravity="center_horizontal"
android:layout_weight="0.29" />
</LinearLayout>
called by "Page1.java"
package com.example.giacomob.myapplication;
import android.app.Activity;
import android.os.Bundle;
/**
* Created by Giacomo B on 05/08/2015.
*/
public class Page1 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page1);
}
}
The MainActivity is:
package com.example.giacomob.myapplication;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ReadXMLFile.readXMLFile(this);
Button b_load=(Button)findViewById(R.id.button_send);
b_load.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent openPage1 = new Intent(MainActivity.this, Page1.class);
startActivity(openPage1);
}
});
}
#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);
}
}
How can I show this string on video in activity_page1?? please, help me.. thanks

Error: Content view not yet created

I'm new to Android development and I have a problem with setting up getting into the next activity when I click an item in my listview within my ListFragment.
When I compile and run the app, it crashes with the error: Content view not yet created. Here is the relevant code. Any help would be much appreciated!
MainActivity:
package com.example.szen95.meddict;
import android.app.SearchManager;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.SearchView;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new SearchFragment())
.commit();
}
getSupportActionBar().setElevation(0f);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
SearchManager searchManager = (SearchManager) getSystemService( Context.SEARCH_SERVICE );
SearchView searchView = (SearchView) menu.findItem( R.id.search_bar ).getActionView();
searchView.setSearchableInfo( searchManager.getSearchableInfo( getComponentName() ) );
return super.onCreateOptionsMenu(menu);
}
#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.
return super.onOptionsItemSelected(item);
}
}
SearchFragment:
package com.example.szen95.meddict;
/**
* Created by szen95 on 6/15/15.
*/
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
/**
* A placeholder fragment containing a simple view.
*/
public class SearchFragment extends ListFragment {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://dailymed.nlm.nih.gov/dailymed/services/v2/drugclasses.json";
// JSON Node names
private static final String TAG_DATA = "data";
private static final String TAG_CODE = "code";
private static final String TAG_CODING_SYSTEM = "codingSystem";
private static final String TAG_TYPE = "type";
private static final String TAG_NAME = "name";
// contacts JSONArray
JSONArray data = null;
// ArrayAdapter<String> mConditionsAdapter;
public SearchFragment() {
}
ArrayList<HashMap<String, String>> dataList;
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
dataList = new ArrayList<HashMap<String, String>>();
// Creating view correspoding to the fragment
View v = inflater.inflate(R.layout.fragment_main, container, false);
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new AdapterView.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 code = ((TextView) view.findViewById(R.id.code))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getActivity().getApplicationContext(),
Details.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_CODE, code);
startActivity(in);
}
});
new GetData().execute();
return v;
}
/**
* Async task class to get json by making HTTP call
* */
private class GetData extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
//
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
data = jsonObj.getJSONArray(TAG_DATA);
// looping through All Contacts
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
String code = c.getString(TAG_CODE);
String codingSystem = c.getString(TAG_CODING_SYSTEM);
String type = c.getString(TAG_TYPE);
String name = c.getString(TAG_NAME);
// tmp hashmap for single contact
HashMap<String, String> data = new HashMap<String, String>();
// adding each child node to HashMap key => value
data.put(TAG_CODE, code);
data.put(TAG_CODING_SYSTEM, codingSystem);
data.put(TAG_TYPE, type);
data.put(TAG_NAME, name);
// adding contact to contact list
dataList.add(data);
}
} 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
* */
SimpleAdapter adapter = new SimpleAdapter(getActivity(), dataList,
R.layout.list_item_search, new String[] { TAG_NAME, TAG_CODE}, new int[] { R.id.name,
R.id.code});
setListAdapter(adapter);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
//
// #Override
// public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// inflater.inflate(R.menu.menu_main, menu);
//
//
// }
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_about) {
// FetchDataTask defTask = new FetchDataTask();
// defTask.execute();
return true;
}
return super.onOptionsItemSelected(item);
}
}
Details:
package com.example.szen95.meddict;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.widget.TextView;
public class Details extends ActionBarActivity {
// JSON node keys
private static final String TAG_NAME = "name";
private static final String TAG_CODE = "code";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String name = in.getStringExtra(TAG_NAME);
String code = in.getStringExtra(TAG_CODE);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblCode = (TextView) findViewById(R.id.code_label);
lblName.setText(name);
lblCode.setText(code);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return onCreateOptionsMenu(menu);
}
}
SearchFragment extends ListFragment. In a ListFragment, getListView() cannot be called in onCreateView(), because onCreateView() is creating the fragment's content view and has not yet completed. The call to getListView() in SearchFragment is the cause of the exception.
Move the the call to getListView() and related to code to one of the fragment lifecycle methods that is called after onCreateView(), such as onViewCreated() or onActivityCreate(). For example:
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new AdapterView.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 code = ((TextView) view.findViewById(R.id.code))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getActivity().getApplicationContext(),
Details.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_CODE, code);
startActivity(in);
}
});
}

Two activities sending data to each other

Two activities are sending data to each other.
The first activity has a custom list view. The second has one text view and three buttons to increase and decrease a value.
When I click on the first activity, the second activity opens. The second activity increases the text view value and clicked the button. Data goes to the first activity. Same process again.
My problem is that the total value is not displayed in the first activity.
How can i show all increase and decrease values from the second activity in the first activity?
First activity's code:
package com.firstchoicefood.phpexpertgroup.firstchoicefoodin;
import android.app.ActionBar;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean.ListModel;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.json.JSONfunctions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
public class DetaisRESTActivity extends Activity {
String messagevaluename,valueid,valueid1,valuename,pos;
public String countString=null;
String nameofsubmenu;
public int count=0;
public String message=null;
public String message1=null;
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ArrayList aa;
public SharedPreferences.Editor edit;
public TextView mTitleTextView;
public ImageButton imageButton;
ListAdapterAddItems adapter;
public TextView restaurantname = null;
public TextView ruppees = null;
ProgressDialog mProgressDialog;
ArrayList<ListModel> arraylist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detais_rest);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ff0000")));
SharedPreferences preferences=getSharedPreferences("temp1", 1);
// SharedPreferences.Editor editor = preferences.edit();
int na=preferences.getInt("COUNTSTRING1",0);
Log.i("asasassas",""+na);
LayoutInflater mInflater = LayoutInflater.from(this);
View mCustomView = mInflater.inflate(R.layout.titlebar, null);
mTitleTextView = (TextView) mCustomView.findViewById(R.id.textView123456789);
imageButton = (ImageButton) mCustomView
.findViewById(R.id.imageButton2);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Refresh Clicked!",
Toast.LENGTH_LONG).show();
Intent i=new Intent(DetaisRESTActivity.this,TotalPriceActivity.class);
startActivity(i);
}
});
actionBar.setCustomView(mCustomView);
actionBar.setDisplayShowCustomEnabled(true);
// SqliteControllerSqliteController db = new SqliteControllerSqliteController(QuentityActivity.this);
// Reading all contacts
/*
Log.d("Reading: ", "Reading all contacts..");
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
String log = "Id: "+cn.getID()+" ,Name: " + cn.getName() + " ,Phone: " +
cn.getPhoneNumber();
// Writing Contacts to log
Log.d("Name: ", log);
}
*/
Intent intent = getIntent();
// get the extra value
valuename = intent.getStringExtra("restaurantmenuname");
valueid = intent.getStringExtra("restaurantmenunameid");
valueid1 = intent.getStringExtra("idsrestaurantMenuId5");
//totalamount = intent.getStringExtra("ruppees");
Log.i("valueid",valueid);
Log.i("valuename",valuename);
Log.i("valueid1",valueid1);
// Log.i("totalamount",totalamount);
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void,Void,Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(DetaisRESTActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
Toast.makeText(DetaisRESTActivity.this, "Successs", Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<ListModel>();
// Retrieve JSON Objects from the given URL address
// Log.i("123",value1);
jsonobject = JSONfunctions.getJSONfromURL("http://firstchoicefood.in/fcfapiphpexpert/phpexpert_restaurantMenuItem.php?r=" + URLEncoder.encode(valuename) + "&resid=" + URLEncoder.encode(valueid1) + "&RestaurantCategoryID=" + URLEncoder.encode(valueid) + "");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("RestaurantMenItems");
Log.i("1234",""+jsonarray);
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
ListModel sched = new ListModel();
sched.setId(jsonobject.getString("id"));
sched.setProductName(jsonobject.getString("RestaurantPizzaItemName"));
sched.setPrice(jsonobject.getString("RestaurantPizzaItemPrice"));
arraylist.add(sched);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listViewdetails);
adapter = new ListAdapterAddItems();
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
adapter.notifyDataSetChanged();
listview.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
{
// Get Person "behind" the clicked item
ListModel p =(ListModel)listview.getItemAtPosition(position);
// Log the fields to check if we got the info we want
Log.i("SomeTag",""+p.getId());
//String itemvalue=(String)listview.getItemAtPosition(position);
Log.i("SomeTag", "Persons name: " + p.getProductName());
Log.i("SomeTag", "Ruppees: " + p.getPrice());
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position + 1),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
Log.i("postititi",""+position);
Intent intent=new Intent(DetaisRESTActivity.this,QuentityActivity.class);
intent.putExtra("quentity",countString);
intent.putExtra("valueid",valueid);
intent.putExtra("valuename",valuename);
intent.putExtra("valueid1",valueid1);
intent.putExtra("id",p.getId());
intent.putExtra("name",p.getProductName());
intent.putExtra("price",p.getPrice());
startActivityForResult(intent,2);
// startActivity(intent);
}
});
}
}
// Call Back method to get the Message form other Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
pos=data.getStringExtra("POSITION");
message=data.getStringExtra("MESSAGE");
message1=data.getStringExtra("COUNTSTRING");
messagevaluename=data.getStringExtra("VALUENAME");
nameofsubmenu=data.getStringExtra("name");
Log.i("xxxxxxxxxxx",message);
Log.i("xxxxxxxxxxx1234",pos);
Log.i("xxxxxxxxxxx5678count",message1);
Log.i("messagevaluename",messagevaluename);
Log.i("submenu",nameofsubmenu);
//ruppees.setText(message);
//editor.putInt("count",na);
//editor.commit();
//Log.i("asasassasasdsasdasd",""+na);
// mTitleTextView.setText(Arrays.toString(message1));
mTitleTextView.setText(message1);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_LONG).show();
Intent i=new Intent(DetaisRESTActivity.this,TotalPriceActivity.class);
i.putExtra("count",message1);
i.putExtra("submenu",nameofsubmenu);
i.putExtra("ruppees",message);
i.putExtra("id",pos);
i.putExtra("messagevaluename",messagevaluename);
startActivity(i);
}
});
}
}
//==========================
class ListAdapterAddItems extends ArrayAdapter<ListModel>
{
ListAdapterAddItems(){
super(DetaisRESTActivity.this,android.R.layout.simple_list_item_1,arraylist);
//imageLoader = new ImageLoader(MainActivity.this);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if(convertView == null){
LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.cartlistitem, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
holder.populateFrom(arraylist.get(position));
// arraylist.get(position).getPrice();
return convertView;
}
}
class ViewHolder {
ViewHolder(View row) {
restaurantname = (TextView) row.findViewById(R.id.rastaurantnamedetailsrestaurant);
ruppees = (TextView) row.findViewById(R.id.rastaurantcuisinedetalsrestaurant);
}
// Notice we have to change our populateFrom() to take an argument of type "Person"
void populateFrom(ListModel r) {
restaurantname.setText(r.getProductName());
ruppees.setText(r.getPrice());
}
}
//=============================================================
#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_detais_rest, 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.
return super.onOptionsItemSelected(item);
}
public void OnPause(){
super.onPause();
}
}
Second activity's code:
package com.firstchoicefood.phpexpertgroup.firstchoicefoodin;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean.CARTBean;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean.ListModel;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.database.SqliteController;
public class QuentityActivity extends Activity {
String value=null;
public String TotAmt=null;
String[] cccc;
ImageButton positive,negative;
String position;
static int count = 1;
int tot_amt = 0;
public String countString=null;
String name,price;
String valueid,valueid1,valuename;
public TextView ruppees,submenuname,totalruppees,quantity,addtocart;
SharedPreferences preferences;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quentity);
ActionBar actionBar = getActionBar();
// Enabling Up / Back navigation
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ff0000")));
preferences = getSharedPreferences("temp1",1);
editor = preferences.edit();
Intent intent = getIntent();
// get the extra value
value = intent.getStringExtra("quentity");
valuename = intent.getStringExtra("valuename");
valueid = intent.getStringExtra("valueid");
valueid1 = intent.getStringExtra("valueid1");
name=intent.getStringExtra("name");
price=intent.getStringExtra("price");
position=intent.getStringExtra("id");
quantity=(TextView)findViewById(R.id.rastaurantcuisinedetalsrestaurantquantity);
totalruppees=(TextView)findViewById(R.id.rastaurantnamequentitytotal1);
submenuname=(TextView)findViewById(R.id.rastaurantnamesubmenuquentity);
ruppees=(TextView)findViewById(R.id.rastaurantnamequentity1);
positive=(ImageButton)findViewById(R.id.imageButtonpositive);
negative=(ImageButton)findViewById(R.id.imageButtonnegative);
addtocart=(TextView)findViewById(R.id.textViewaddtocart);
buttonclick();
addtocart();
submenuname.setText(name);
ruppees.setText(price);
totalruppees.setText(price);
// new DownloadJSON().execute();
}
public void buttonclick(){
positive.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String totalAmtString = ruppees.getText().toString();
int totAmount = Integer.parseInt(totalAmtString);
//count = Integer.parseInt(getString);
count++;
editor.putInt("COUNTSTRING1", count);
editor.commit();
editor.clear();
Log.i("sunder sharma",""+count);
countString= String.valueOf(count);
tot_amt = totAmount * count;
TotAmt = String.valueOf(tot_amt);
totalruppees.setText(TotAmt);
quantity.setText(countString);
}
});
negative.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String totalAmtString = ruppees.getText().toString();
int totAmount = Integer.parseInt(totalAmtString);
if (count > 1)
count--;
editor.putInt("COUNTSTRING1", count);
editor.commit();
countString = String.valueOf(count);
tot_amt = totAmount * count;
TotAmt = String.valueOf(tot_amt);
totalruppees.setText(TotAmt);
quantity.setText(countString);
}
});
}
public void addtocart(){
addtocart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* Log.i("valueid",valueid);
Log.i("valuename",valuename);
Log.i("valueid1",valueid1);
Log.i("name",name);
Log.i("price",price);
Log.i("id1",position);
SqliteController db = new SqliteController(QuentityActivity.this);
db.insertStudent(new CARTBean(position,name,price,countString,TotAmt));
*/
Intent intent=new Intent();
intent.putExtra("MESSAGE",TotAmt);
intent.putExtra("POSITION",position);
intent.putExtra("COUNTSTRING",countString);
intent.putExtra("VALUENAME",valuename);
intent.putExtra("name",name);
setResult(2,intent);
finish();//finishing activity
}
});
}
#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_quentity, 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);
}
}
Collect the data from second activity and put into below intent .Then you will receive first activity.
Intent myIntent = new Intent(secondActivity.this, firstActivity.class);
myIntent.putExtra("COUNTSTRING", CountString); //add data
startActivity(myIntent);

list of images not showing up after search button is pressed

I am getting image urls using google image search apis. i use okhttp to connect to the url. this is done in my activity's oncreate method. in the oncreate() method of fragment i get all the image urls and store them in mSmallIMagesUrl, in the oncreateView() i try to display the images using a customized adapter. but when i run my app, hit the search button, it shows a blank page, when i go back and click the search button(there is always text in the search box) it shows images of the the previous search text. i dont know why it this,below is my code, please let me know what i am missing. thanks
package com.paveynganpi.allsearch;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.io.IOException;
import java.util.ArrayList;
public class ImageGrid extends ActionBarActivity {
private static final String TAG = ImageGrid.class.getSimpleName();
protected int start = 0;//variable to change pages from google Api
//contains extra images urls to supply to ... when need
protected static ArrayList<ArrayList<String>> mBigImagesUrls = new ArrayList<ArrayList<String>>();
//contains image urls to inject into gridview
protected static ArrayList<String> mSmalImagesUrls = new ArrayList<>();
protected static String mEditedString;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_grid);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
for (int start = 0; start < 2; start++) {
if (isNetworkAvailable()) {
//using okHttp library to connect to imagesUrl and retrieve JSON Data
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(getImagePage(start)).
build();
Call call = client.newCall(request);
//runs the below code asynchronously
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
Log.v(TAG, "error from request");
}
#Override
public void onResponse(Response response) throws IOException {
try {
String jsonData = response.body().string();
//Log.v(TAG, jsonData);
if (!response.isSuccessful()) {
alertUserAboutError();
} else {
// mSmalImagesUrls = getCurrentDetails(jsonData);
mBigImagesUrls.add(getCurrentDetails(jsonData));
Log.d(TAG, mBigImagesUrls.size() + " big size");
Log.d(TAG, mSmalImagesUrls.size() + " small size");
}
} catch (IOException | JSONException e) {
Log.e(TAG, "Exception caught :", e);
}
}
});
} else {
Toast.makeText(this, "Network is unavailable", Toast.LENGTH_LONG).show();
}
}
}
#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_image_grid, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private String getImagePage(int start) {
return "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q="
+ mEditedString + "&rsz=8&start=" + start;
}
//get data
private ArrayList<String> getCurrentDetails(String jsonData) throws JSONException {
JSONObject jsonObject = new JSONObject(jsonData);
JSONObject responseData = jsonObject.getJSONObject("responseData");
ArrayList<String> localList = new ArrayList<String>();
JSONArray results = responseData.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
localList.add(results.getJSONObject(i).getString("url"));
}
return localList;
}
//An AlertDialog to display to user when an error occurs
private void alertUserAboutError() {
AlertDialogFragment dialog = new AlertDialogFragment();
dialog.show(getFragmentManager(), "error_dialog");
}
//checks if user is connected to a network
private boolean isNetworkAvailable() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isAvailable = false;
if (activeNetwork != null && activeNetwork.isConnectedOrConnecting()) {
isAvailable = true;
}
return isAvailable;
}
#Override
public void onBackPressed() {
super.onBackPressed();
Log.d(TAG,"back was pressed");
mBigImagesUrls.clear();
mSmalImagesUrls.clear();
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
protected GridView mGridView;//reference to gridview in fragment_image_grid.xml
static String mEditedString;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, mBigImagesUrls.size() + " final big size");
Log.d(TAG, mSmalImagesUrls.size() + "final small size");
for(int i =0;i<mBigImagesUrls.size();i++){
for(int j =0;j<8;j++){
mSmalImagesUrls.add(mBigImagesUrls.get(i).get(j));
}
}
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_image_grid, container, false);
final ArrayList<String> testList = new ArrayList<String>();
//gets the edited string from MainActivity
Bundle args = getActivity().getIntent().getExtras();
mEditedString = args.getString("space");
mGridView = (GridView)rootView.findViewById(R.id.imagesGrid);//reference to gridview
ImagesGridAdapter adapter = new ImagesGridAdapter(getActivity(), mSmalImagesUrls);
mGridView.setAdapter(adapter);
return rootView;
}
}
}
Since you are making an asynchronous request, the response is not available immediately. You can display a ProgressBar while the list of images is being downloaded, and then display the list when it has completed downloading.
After that, notify your adapter that the dataset has changed.

parse object not receiving

I get the Id for a parse object from a previous activity and store it in "obj"
I know the Id is being passed by checking but am getting null pointer exceptions because my four strings restName,restAddress,restCuisine and restLocation are empty even after i try assigning the corresponding values by my parse query.
package com.example.gastronomaapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.parse.GetCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
public class SingleRestraunt extends ActionBarActivity {
private GoogleMap map;
TextView resteName, resteCuisine, resteLocation, resteAddress;
String restName = "nothing", obj, restCuisine = "nothing",
restLocation = "nothing", restAddress = "nothing";
Double Lang, Long;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_restraunt);
Intent i = getIntent();
obj = i.getStringExtra("restName");
getDetails(obj);
}
private void getDetails(String obj) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("Restraunt");
query.getInBackground(obj, new GetCallback<ParseObject>() {
#Override
public void done(ParseObject object, ParseException e) {
if (e == null) {
restName = object.getString("Name");
restCuisine = object.getString("Cuisine");
restLocation = object.getString("Location");
restAddress = object.getString("Address");
Lang = object.getDouble("Lat");
Long = object.getDouble("Long");
} else {
e.printStackTrace();
}
}
});
// prepareMap(Lang, Long);
addData();
}
public void addData() {
resteName = (TextView) findViewById(R.id.restrauntName);
resteCuisine = (TextView) findViewById(R.id.restrauntCuisine);
resteLocation = (TextView) findViewById(R.id.restrauntLocation);
resteAddress = (TextView) findViewById(R.id.restrauntAddress);
resteName.setText(restName);
resteCuisine.setText(restCuisine);
resteLocation.setText(restLocation);
resteAddress.setText(restAddress);
}
public void prepareMap(Double Lang, Double Long) {
final LatLng REST = new LatLng(Lang, Long);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
#SuppressWarnings("unused")
Marker hamburg = map.addMarker(new MarkerOptions().position(REST)
.title("Here"));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(REST, 15));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.single_restraunt, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void Submit(View v) {
final EditText edit = (EditText) findViewById(R.id.review);
final EditText edit1 = (EditText) findViewById(R.id.rName);
String rName = edit1.getText().toString();
String review = edit.getText().toString();
ParseObject newReview = new ParseObject("Reviews");
newReview.put("Name", rName);
newReview.put("review", review);
newReview.saveInBackground();
}
}
I added the nothing value to all my strings initially to debug. And when running promptly the nothing is printed indicating that the query is not making any change to my strings.Any suggestions?

Categories

Resources