How do I pass the data from this to the next activity passing a particular data? I use PHP+MySQL and Java on Android.
I call this by using onClick on the button:
public class LoginActivity extends Activity {
Handler h = new Handler();
/*
* Login
*/
public void Login(View view) {
EditText usernameField = (EditText)findViewById(R.id.editText_Username_L);
EditText passwordField = (EditText)findViewById(R.id.editText_Password_L);
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
new SigninActivity(this).execute(username,password);
}
/*
* Login
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, 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);
}
}
This is where my code passes and gets data:
public class SigninActivity extends AsyncTask<String,Void,String> {
private TextView roleField;
private Context context;
public SigninActivity(Context context) {
this.context = context;
}
protected void onPreExecute(){
}
#Override
protected String doInBackground(String... arg0) {
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link="http://192.168.254.108/Login/login.php";
String data = URLEncoder.encode("username", "UTF-8")
+ "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8")
+ "=" + URLEncoder.encode(password, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter
(conn.getOutputStream());
wr.write( data );
wr.flush();
BufferedReader reader = new BufferedReader
(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result){
this.roleField.setText(result);
if(result.equals("")){
Intent i = new Intent(SigninActivity.this, DashboardActivity.class);
i.putExtra("user_id", result);
startActivity(i)
} else {
}
}
}
My PHP code:
<?php
$con=mysqli_connect("localhost","root","","d_database");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysqli_query($con,"SELECT id FROM user where
username='$username' and password='$password'");
$row = mysqli_fetch_array($result);
$data = $row[0];
if($data){
echo $data;
}
mysqli_close($con);
?>
So I answered it, I guess I didn't do enough research.
Here's my code:
public class LoginActivity extends Activity {
Handler h = new Handler();
/*
* Login
*/
public void DishcoverLogin(View view) {
EditText usernameField = (EditText)findViewById(R.id.editText_Username_L);
EditText passwordField = (EditText)findViewById(R.id.editText_Password_L);
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
new SigninActivity(this).execute(username,password);
}
/*
* Login
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, 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 SigninActivity extends AsyncTask<String,Void,String> {
private TextView roleField;
private Context context;
public SigninActivity(Context context) {
this.context = context;
}
protected void onPreExecute(){
}
#Override
protected String doInBackground(String... arg0) {
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link="http://192.168.254.108/Login/d_login.php";
String data = URLEncoder.encode("username", "UTF-8")
+ "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8")
+ "=" + URLEncoder.encode(password, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter
(conn.getOutputStream());
wr.write( data );
wr.flush();
BufferedReader reader = new BufferedReader
(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result){
String vl=result.toString();
if(vl.equals("registered")){
AlertDialog.Builder alt_bld = new AlertDialog.Builder(LoginActivity.this);
alt_bld.setMessage("D Login Successfull !")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'Yes' Button
EditText username = (EditText) findViewById(R.id.editText_Username_L);
EditText password = (EditText) findViewById(R.id.editText_Password_L);
Intent in = new Intent(getApplicationContext(), DashboardActivity.class);
in.putExtra("username", username.toString());
in.putExtra("password", password.toString());
startActivity(in);
finish();
}
});
AlertDialog alert = alt_bld.create();
// Title for AlertDialog
alert.setTitle("D Login");
// Icon for AlertDialog
alert.setIcon(R.drawable.topbar);
alert.show();
} else {
AlertDialog.Builder alt_bld = new AlertDialog.Builder(LoginActivity.this);
alt_bld.setMessage("D Login Unsuccessfull !")
.setCancelable(false)
.setNegativeButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'NO' Button
dialog.cancel();
}
});
AlertDialog alert = alt_bld.create();
// Title for AlertDialog
alert.setTitle("D Login");
// Icon for AlertDialog
alert.setIcon(R.drawable.topbar);
alert.show();
}
}
}
}
Related
I am the student and i'm learning android, i got following error and i can't find out the solution of that error, plz help me to solve that error. Thank you...
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.sumit.json1/com.sumit.json1.ParseJSON}:
java.lang.NullPointerException: Attempt to invoke virtual method
'org.json.JSONObject org.json.JSONArray.getJSONObject(int)' on a null object
reference.
There is no issue of connectivity to database. My php code is which is hosted on hostinger.in
<?
//these are the server details
//the username is root by default in case of xampp
//password is nothing by default
//and lastly we have the database named android. if your database name is
different you have to change it
$servername = "mysql.hostinger.in";
$username = "username";
$password = "*********";
$database = "database_name";
//creating a new connection object using mysqli
$conn = new mysqli($servername, $username, $password, $database);
//if there is some error connecting to the database
//with die we will stop the further execution by displaying a message
causing the error
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//if everything is fine
//creating an array for storing the data
$heroes = array();
//this is our sql query
$sql = "SELECT id, name, email, username, password, gender, lat, lon FROM
appusers;";
//creating an statment with the query
$stmt = $conn->prepare($sql);
//executing that statment
$stmt->execute();
//binding results for that statment
$stmt->bind_result($id, $name, $email, $username, $password, $gender, $lat,
$lon);
//looping through all the records
while($stmt->fetch()){
//pushing fetched data in an array
$temp = [
'id'=>$id,
'name'=>$name,
'email'=>$email,
'username'=>$username,
'password'=>$password,
'gender'=>$gender,
'lat'=>$lat,
'lon'=>$lon
];
//pushing the array inside the hero array
array_push($heroes, $temp);
}
//displaying the data in json format
echo json_encode($heroes);
For parsing json my android code is i.e. ParseJSON.java
public class ParseJSON extends ActionBarActivity implements
View.OnClickListener{
private String myJSONString;
private static final String JSON_ARRAY ="heroes";
private static final String ID = "id";
private static final String NAME= "name";
private static final String EMAIL = "email";
private static final String USERNAME= "username";
private static final String PASSWORD = "password";
private static final String GENDER = "gender";
private static final String LAT = "lat";
private static final String LON = "lon";
private JSONArray users = null;
private int TRACK = 0;
private EditText editTextId;
private EditText editTextName;
private EditText editTextEmail;
private EditText editTextUserName;
private EditText editTextPassword;
private EditText editTextGender;
private EditText editTextLat;
private EditText editTextLon;
Button btnPrev;
Button btnNext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_parse_json);
Intent intent = getIntent();
myJSONString = intent.getStringExtra(MainActivity.MY_JSON);
editTextId = (EditText) findViewById(R.id.editTextID);
editTextName = (EditText) findViewById(R.id.editTextName);
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextUserName = (EditText) findViewById(R.id.editTextUsername);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
editTextGender = (EditText) findViewById(R.id.editTextGender);
editTextLat = (EditText) findViewById(R.id.editTextLat);
editTextLon = (EditText) findViewById(R.id.editTextLon);
btnPrev = (Button) findViewById(R.id.buttonPrev);
btnNext = (Button) findViewById(R.id.buttonNext);
btnPrev.setOnClickListener(this);
btnNext.setOnClickListener(this);
extractJSON();
showData();
}
private void extractJSON(){
try {
JSONObject jsonObject = new JSONObject(myJSONString);
users = jsonObject.getJSONArray(JSON_ARRAY);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void moveNext(){
if(TRACK<users.length()){
TRACK++;
}
showData();
}
private void movePrev(){
if(TRACK>0){
TRACK--;
}
showData();
}
private void showData(){
try {
JSONObject jsonObject = users.getJSONObject(TRACK);
editTextId.setText(jsonObject.getString(ID));
editTextName.setText(jsonObject.getString(NAME));
editTextEmail.setText(jsonObject.getString(EMAIL));
editTextUserName.setText(jsonObject.getString(USERNAME));
editTextPassword.setText(jsonObject.getString(PASSWORD));
editTextGender.setText(jsonObject.getString(GENDER));
editTextLat.setText(jsonObject.getString(LAT));
editTextLon.setText(jsonObject.getString(LON));
} catch (JSONException e) {
e.printStackTrace();
}
}
#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_parse_json, 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);
}
#Override
public void onClick(View v) {
if(v == btnNext){
moveNext();
}
if(v == btnPrev){
movePrev();
}
}
}
In my android project MainActivity.java is given bellow if any error find out plz help me to resove
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
private TextView textViewJSON;
private Button buttonGet;
private Button buttonParse;
public static final String MY_JSON ="MY_JSON";
private static final String JSON_URL = "http://mydatabasedb.16mb.com/JSON1/send-data1.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewJSON = (TextView) findViewById(R.id.textViewJSON);
textViewJSON.setMovementMethod(new ScrollingMovementMethod());
buttonGet = (Button) findViewById(R.id.buttonGet);
buttonParse = (Button) findViewById(R.id.buttonParse);
buttonGet.setOnClickListener(this);
buttonParse.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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);
}
#Override
public void onClick(View v) {
if(v==buttonGet){
getJSON(JSON_URL);
}
if(v==buttonParse){
showParseActivity();
}
}
private void showParseActivity() {
Intent intent = new Intent(this, ParseJSON.class);
intent.putExtra(MY_JSON,textViewJSON.getText().toString());
startActivity(intent);
}
private void getJSON(String url) {
class GetJSON extends AsyncTask<String, Void, String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Please Wait...",null,true,true);
}
#Override
protected String doInBackground(String... params) {
String uri = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while((json = bufferedReader.readLine())!= null){
sb.append(json+"\n");
}
return sb.toString().trim();
}catch(Exception e){
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
textViewJSON.setText(s);
}
}
GetJSON gj = new GetJSON();
gj.execute(url);
}
}
users = jsonObject.getJSONArray(JSON_ARRAY);
This attempts to parse a list at the "heroes" key, but there is no "heroes" key the JSON document. You are encoding a list, not an object.
Open the URL that returns the JSON in a browser, and the problem should be apparent.
Im attempting to have a login that checks to see if user exists on a mysql database, but when running the app it remembers previous login details. I think the problem is in the background task as if I comment it out I can toast the login details fine.
public class Tab1Activity extends Activity
{
String task,username,password;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.tab1);
final Button buta = (Button) findViewById(R.id.button1);
final Button butb = (Button) findViewById(R.id.button2);
final TextView usernameTV = (TextView) findViewById(R.id.editText1);
final TextView passwordTV = (TextView) findViewById(R.id.editText2);
buta.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
SharedPreferences preferences = getSharedPreferences("MYPREFS", Context.MODE_PRIVATE);
//editor = preferences.edit();
username=usernameTV.getText().toString();
password=passwordTV.getText().toString();
task="login";
Toast.makeText(getApplicationContext(), username+" "+password, Toast.LENGTH_SHORT).show();
// create and call background activity
BackgroundTask backgroundTaskLogin = new BackgroundTask(Tab1Activity.this);
backgroundTaskLogin.execute(task,username,password);
//get data back from sharedpreference
String driver_exist = preferences.getString("myDatalogin","ERROR getting name");
//display datas
String[] loginSeparated = driver_exist.split(",");
Toast.makeText(getApplicationContext(), loginSeparated[0], Toast.LENGTH_SHORT).show();
if (loginSeparated[0].equals("true"))
{
int finalId = Integer.parseInt(loginSeparated[1]);
//Toast.makeText(getApplicationContext(), loginSeparated[1], Toast.LENGTH_SHORT).show();
SharedPreferences.Editor editor = getSharedPreferences("MYPREFS", Context.MODE_PRIVATE).edit();
editor.putInt("TaxiDriverId", finalId);
editor.apply();
//once clicked - jump to tab2
TabActivity tabs = (TabActivity) getParent();
tabs.getTabHost().setCurrentTab(1);
}
else
{
Toast.makeText(getApplicationContext(), "Wrong password", Toast.LENGTH_SHORT).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.tab1, 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);
}
}
This is the background talk which I believe where the problem lie.
public class BackgroundTask extends AsyncTask<String,Void,String>
{
SharedPreferences preferences;
SharedPreferences.Editor editor;
SharedPreferences.Editor pig;
Context context;
BackgroundTask(Context ctx)
{
this.context = ctx;
}
#Override
protected String doInBackground(String... params)
{
String urlLogin = "";
preferences = context.getSharedPreferences("MYPREFS", Context.MODE_PRIVATE);
editor = preferences.edit();
editor.putString("flag","0");
editor.commit();
String task = params[0];
String loginusername;
String loginpassword;
if (task.equals("login"))
{
urlLogin = "http://super.com/LoginAndRegister-login.php";
loginusername = params[1];
loginpassword = params[2];
try
{
URL url = new URL(urlLogin);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
//send the driver number to the database
OutputStream outputStream = httpURLConnection.getOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream,"UTF-8");
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
String myDatalogin = URLEncoder.encode("identifier_loginEmail","UTF-8")+"="+URLEncoder.encode(loginusername,"UTF-8")
+"&"+URLEncoder.encode("identifier_loginPassword","UTF-8")+"="+URLEncoder.encode(loginpassword,"UTF-8");
bufferedWriter.write(myDatalogin);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
//get response from the database
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String dataResponse = "";
String inputLine = "";
while((inputLine = bufferedReader.readLine()) != null)
{
dataResponse += inputLine;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
editor.putString("flag","login");
editor.commit();
pig = preferences.edit();
pig.putString("myDatalogin",dataResponse);
pig.commit();
return dataResponse;
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}//end if statement
When you're done with the Activity call finish() this will ensure that the next time the activity is started it will start fresh. Also look over the launchMode attribute in the Activity tag in AndroidManifest.xml to make sure you're starting your activity correctly. https://developer.android.com/guide/topics/manifest/activity-element.html
Hey Guys I'm working on a calorie app where the user clicks the search button and it supposed to retrieve information from the USDA Food Composition Databases API. For some reason it doesnt do anything and I noticed I get an error in the Logcat.
Im new to Android and to API. Thanks again in advance..
logcat :
Here is the logcat Error I'm Getting
AddEntry.java
public class AddEntry extends Fragment implements View.OnClickListener {
EditText FoodET,CalorieET;
ImageButton Savebtn, Cancelbtn;
Button searchbutton;
String foodET,calorieET;
//database
private DatabaseHandler dba;
public AddEntry() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View myView = inflater.inflate(R.layout.fragment_add_entry, container,
false);
Savebtn = (ImageButton) myView.findViewById(R.id.SaveBtn);
Savebtn.setBackgroundColor(Color.TRANSPARENT);
Savebtn.setOnClickListener(this);
searchbutton = (Button) myView.findViewById(R.id.SearchButton);
searchbutton.setOnClickListener(this);
Cancelbtn = (ImageButton) myView.findViewById(R.id.CancelBtn);
Cancelbtn.setBackgroundColor(Color.TRANSPARENT);
Cancelbtn.setOnClickListener(this);
return myView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
FoodET= (EditText)view.findViewById(R.id.foodEditText);
FoodET.setInputType(InputType.TYPE_CLASS_TEXT);
CalorieET=(EditText)view.findViewById(R.id.caloriesEditText);
CalorieET.setInputType(InputType.TYPE_CLASS_NUMBER);
foodET = ((EditText)
view.findViewById(R.id.foodEditText)).getText().toString();
calorieET = ((EditText)
view.findViewById(R.id.caloriesEditText)).getText().toString();
}
public void saveDataToDB (){
Food food = new Food();
String FoodName = FoodET.getText().toString().trim();
String calString = CalorieET.getText().toString().trim();
//convert the claories numbers to text
if (!calString.equals("")) {
int cal = Integer.parseInt(calString);
food.setFoodName(FoodName);
food.setCalories(cal);
//call addFood method from the DatabaseHandler
dba.addFood(food);
dba.close();
//clear the editTexts
FoodET.setText("");
CalorieET.setText("");
//take the user to the next screen
//
((appMain) getActivity()).loadSelection(0);
;
}
else
{
Toast.makeText(getActivity(), "Please enter information",
Toast.LENGTH_LONG).show();
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.SearchButton:
InputMethodManager inputManager = (InputMethodManager)
getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(
getActivity().getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
FoodSearch search = new FoodSearch(foodET,CalorieET );
search.execute();
break;
case R.id.SaveBtn:
foodET = FoodET.getText().toString();
calorieET=CalorieET.getText().toString();
if (FoodET.getText().toString().equals(null) ||
CalorieET.getText().toString().equals(null)||
CalorieET.getText().toString().equals("")){
Toast.makeText(getActivity(), "Please enter information",
Toast.LENGTH_LONG).show();
}
((appMain) getActivity()).loadSelection(0);
break;
case R.id.CancelBtn:
// EditText descriptionET=
(EditText)getView().findViewById(R.id.foodEditText);
//descriptionET.setText("");
//EditText calorieET=
(EditText)getView().findViewById(R.id.caloriesEditText);
//calorieET.setText("");
((appMain) getActivity()).loadSelection(0);
break;
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
private class FoodSearch extends AsyncTask<Void, Void, String> {
String food;
EditText calories;
FoodSearch(String food, EditText calories){
this.food = food;
this.calories = calories;
}
#Override
protected String doInBackground(Void... params) {
try {
food = food.replaceAll(" ", "%20");
URL url = new URL("http://api.nal.usda.gov/ndb/search/?
format=JSON&q=" + food
+"&max=1&offset=0&sort=r&api_
key=2PmoCzLAhkNUeJcwq2VfOaSNY66UgFVDEcco2qMP");
HttpURLConnection urlConnection = (HttpURLConnection)
url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
String result = stringBuilder.toString();
if(result.contains("zero results")) {
String s = "empty";
return s;
}
JSONObject object = (JSONObject) new
JSONTokener(result).nextValue();
JSONObject list = object.getJSONObject("list");
JSONArray items = list.getJSONArray("item");
String item = items.get(0).toString();
int i = item.indexOf("ndbno\":\"") + 8;
int f = item.indexOf("\"", i);
String ndbno = item.substring(i,f);
Log.d("DEBUG", ndbno);
URL url2 = new URL("http://api.nal.usda.gov/ndb/reports/?
ndbno="+ ndbno +"&type=b&format=JSON&api_
key=2PmoCzLAhkNUeJcwq2VfOaSNY66UgFVDEcco2qMP");
HttpURLConnection urlConnection2 = (HttpURLConnection)
url2.openConnection();
BufferedReader bufferedReader2 = new BufferedReader(new
InputStreamReader(urlConnection2.getInputStream()));
StringBuilder stringBuilder2 = new StringBuilder();
String line2;
while ((line2 = bufferedReader2.readLine()) != null) {
stringBuilder2.append(line2).append("\n");
}
bufferedReader2.close();
String res = stringBuilder2.toString();
int index = res.indexOf("\"unit\": \"kcal\",") + 46;
int index2 = res.indexOf("\"", index);
String calories = res.substring(index,index2);
urlConnection2.disconnect();
return calories;
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
String s = "empty";
return s;
}
}
protected void onPostExecute(String response) {
if(!response.isEmpty() && !response.equals("empty")) {
calories.setText(response);
} else {
AlertDialog foodNotFound = new
AlertDialog.Builder(getContext()).create();
foodNotFound.setTitle("Error");
foodNotFound.setMessage("Food not found :(");
foodNotFound.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int
which) {
dialog.dismiss();
}
});
}
}
}
}
You Can call the Async task within the same class and SHow alert dialog in the onPost execute section
public class AddEntry extends Fragment implements View.OnClickListener {
EditText DescriptionET,CalorieET; ImageButton Savebtn, Cancelbtn; Button searchbutton; String description , calorieAmt; //database
private DatabaseHandler dba;
public AddEntry() {
// Required empty public constructor
}
#Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) { // Inflate the layout for this fragment View myView = inflater.inflate(R.layout.fragment_add_entry, container, false);
Savebtn = (ImageButton) myView.findViewById(R.id.SaveBtn);
Savebtn.setBackgroundColor(Color.TRANSPARENT);
Savebtn.setOnClickListener(this);
searchbutton = (Button) myView.findViewById(R.id.SearchButton);
searchbutton.setOnClickListener(this);
Cancelbtn = (ImageButton) myView.findViewById(R.id.CancelBtn);
Cancelbtn.setBackgroundColor(Color.TRANSPARENT);
Cancelbtn.setOnClickListener(this);
return myView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
DescriptionET= (EditText)view.findViewById(R.id.foodEditText);
DescriptionET.setInputType(InputType.TYPE_CLASS_TEXT);
CalorieET=(EditText)view.findViewById(R.id.caloriesEditText);
CalorieET.setInputType(InputType.TYPE_CLASS_NUMBER);
//save to database:
}
public void saveDataToDB (){
Food food = new Food();
String name = DescriptionET.getText().toString().trim();
String calString = CalorieET.getText().toString().trim();
//convert the claories numbers to text
if (!calString.equals("")) {
int cal = Integer.parseInt(calString);
food.setFoodName(name);
food.setCalories(cal);
//call addFood method from the DatabaseHandler
dba.addFood(food);
dba.close();
//clear the editTexts
DescriptionET.setText("");
CalorieET.setText("");
//take the user to the next screen
//
((appMain) getActivity()).loadSelection(0);
;
}
else
{
Toast.makeText(getActivity(), "Please enter information",
Toast.LENGTH_LONG).show();
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.SearchButton:
InputMethodManager inputManager = (InputMethodManager)
getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(
getActivity().getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
FoodSearch search = new FoodSearch(description,CalorieET);
search.execute();
break;
case R.id.SaveBtn:
description = DescriptionET.getText().toString();
calorieAmt=CalorieET.getText().toString();
if (DescriptionET.getText().toString().equals(null) ||
CalorieET.getText().toString().equals(null)||
CalorieET.getText().toString().equals("")){
Toast.makeText(getActivity(), "Please enter information",
Toast.LENGTH_LONG).show();
}
((appMain) getActivity()).loadSelection(0);
break;
case R.id.CancelBtn:
// EditText descriptionET=
(EditText)getView().findViewById(R.id.foodEditText);
//descriptionET.setText("");
//EditText calorieET=
(EditText)getView().findViewById(R.id.caloriesEditText);
//calorieET.setText("");
((appMain) getActivity()).loadSelection(0);
break;
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
}
private class FoodSearch extends AsyncTask<Void, Void, String>{
String food;
EditText calories;
FoodSearch(String food, EditText calories){
this.food = food;
this.calories = calories;
}
#Override
protected String doInBackground(Void... params) {
try {
food = food.replaceAll(" ", "%20");
URL url = new URL("http://api.nal.usda.gov/ndb/search/?
format=JSON&q=" + food +"&max=1&offset=0&sort=r&api_key=2PmoCzLAhkNUeJcwq2VfOaSNY66UgFVDEcco2qMP");
HttpURLConnection urlConnection = (HttpURLConnection)
url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
String result = stringBuilder.toString();
if(result.contains("zero results")) {
String s = "empty";
return s;
}
JSONObject object = (JSONObject) new
JSONTokener(result).nextValue();
JSONObject list = object.getJSONObject("list");
JSONArray items = list.getJSONArray("item");
String item = items.get(0).toString();
int i = item.indexOf("ndbno\":\"") + 8;
int f = item.indexOf("\"", i);
String ndbno = item.substring(i,f);
Log.d("DEBUG", ndbno);
URL url2 = new URL("http://api.nal.usda.gov/ndb/reports/?ndbno="+ ndbno +"&type=b&format=JSON&api_key=2PmoCzLAhkNUeJcwq2VfOaSNY66UgFVDEcco2qMP");
HttpURLConnection urlConnection2 = (HttpURLConnection)
url2.openConnection();
BufferedReader bufferedReader2 = new BufferedReader(new
InputStreamReader(urlConnection2.getInputStream()));
StringBuilder stringBuilder2 = new StringBuilder();
String line2;
while ((line2 = bufferedReader2.readLine()) != null) {
stringBuilder2.append(line2).append("\n");
}
bufferedReader2.close();
String res = stringBuilder2.toString();
int index = res.indexOf("\"unit\": \"kcal\",") + 46;
int index2 = res.indexOf("\"", index);
String calories = res.substring(index,index2);
urlConnection2.disconnect();
return calories;
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
String s = "empty";
return s;
}
}
protected void onPostExecute(String response) {
if(!response.isEmpty() && !response.equals("empty")) {
calories.setText(response);
} else {
AlertDialog foodNotFound = new
AlertDialog.Builder(getContext()).create();
foodNotFound.setTitle("Error");
foodNotFound.setMessage("Food not found :(");
foodNotFound.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
}
}
}
I am using the following MainActivity, and I am still getting the following error message:
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.widget.Toast$TN.<init>(Toast.java:344)
at android.widget.Toast.<init>(Toast.java:100)
at android.widget.Toast.makeText(Toast.java:258)
at com.example.edtomach.whatstheweather.MainActivity$DownloadTask.doInBackground(MainActivity.java:114)
at com.example.edtomach.whatstheweather.MainActivity$DownloadTask.doInBackground(MainActivity.java:80)
Why am I getting this error? The relevant code is here:
public class MainActivity extends Activity {
EditText cityname;
TextView resulttextview;
public void findWeather(View view) {
Log.i("cityname", cityname.getText().toString());
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(cityname.getWindowToken(), 0);
try {
String encodedCityName = URLEncoder.encode(cityname.getText().toString(), "UTF-8");
DownloadTask task = new DownloadTask();
task.execute("http://api.openweathermap.org/data/2.5/weather?q=" + encodedCityName);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "could not find weather", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cityname = (EditText) findViewById(R.id.cityname);
resulttextview = (TextView) findViewById(R.id.resulttextview);
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "could not find weather", Toast.LENGTH_LONG).show();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
String message = "";
JSONObject jsonObject = new JSONObject(result);
String weatherInfo = jsonObject.getString("weather");
Log.i("Weather content", weatherInfo);
JSONArray arr = new JSONArray(weatherInfo);
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
String main = "";
String description = "";
main = jsonPart.getString("main");
description = jsonPart.getString("description");
if (main != "" && description != "") {
message += main + ": " + description + "\r\n";
}
}
if (message != "") {
resulttextview.setText(message);
} else {
Toast.makeText(getApplicationContext(), "could not find weather", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "could not find weather", 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_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);
}
}
do not put anything can modife the main thread on the doBackground methods which herited from asynctask process , in your case you put toast message when you catch exception :
Toast.makeText(getApplicationContext(), "could not find weather", Toast.LENGTH_LONG).show();
instead that use logger message like e.g: Log.(TAG, "your message");
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I want to implement search in my listview which is made by custom listadatper, I am parsing data from JSON and saving it into internal storage, here is my code
package life.quran.com.quranlife;
public class MainActivity extends ActionBarActivity {
List<Surah> surahList;
ListView lv;
EditText searchtxt;
ArrayList<String> surahNames;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar ab = getSupportActionBar();
ab.hide();
searchtxt = (EditText) findViewById(R.id.txtsearch);
surahList = new ArrayList<>();
lv = (ListView) findViewById(R.id.listView);
File f = getFilesDir();a
String filepath = f.getAbsolutePath();
File _file = new File(filepath + "/surah.json");
if (isOnline()) {
surahTask task = new surahTask();
task.execute("http://quran.life/surah.php");
} else {
String offline_data = readFromFile();
surahList = SurahJsonParser.parseData(offline_data);
displaySurah();
}
}
#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;
}
protected void displaySurah() {
final SurahAdapter adapter = new SurahAdapter(MainActivity.this,R.layout.item_template,surahList);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Surah surah = adapter.getItem(position);
String surahNo = surah.getSurah_no().toString();
String suranName = surah.getSurah_name().toString();
Intent intent = new Intent(MainActivity.this, SurahDetailsActivity.class);
intent.putExtra("_sno", surahNo);
intent.putExtra("_sname", suranName);
startActivity(intent);
}
});
searchtxt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
/* Surah surahItems = new Surah();
List<Surah> newlist = new ArrayList<Surah>();
ArrayList<String> temp = new ArrayList<String>();
int textlength = searchtxt.getText().length();
newlist.clear();
for(int i = 0; i < surahNames.size(); i++) {
if(textlength <= surahNames.get(i).length()) {
if(searchtxt.getText().toString().equalsIgnoreCase((String)surahNames.get(i).subSequence(0,textlength))) {
newlist.add(surahNames.get(i));
}
}
}
lv.setAdapter(new SurahAdapter(MainActivity.this,R.layout.item_template,surahList));
*/
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
private boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
private void writeToFile(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("surah.json", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
private String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput("surah.json");
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
} catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
#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 class surahTask extends AsyncTask<String, String, String> {
ProgressDialog pd;
#Override
protected void onPreExecute() {
pd = new ProgressDialog(MainActivity.this);
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.setTitle("Please Wait...");
pd.setMessage("Preparing List Of Surah..");
pd.setIndeterminate(false);
pd.setCancelable(false);
pd.show();
}
#Override
protected String doInBackground(String... params) {
surahNames = new ArrayList<>();
String content = HttpManager.getData(params[0]);
for(Surah surah : surahList) {
surahNames.add("Surah " +surah.getSurah_name());
}
writeToFile(content);
return content ;
}
#Override
protected void onPostExecute(String s) {
surahList = SurahJsonParser.parseData(s);
displaySurah();
pd.dismiss();
}
}
}
Edited
To implement search, you need to use the textchanged event of the editText which will take the search word as an input. You can read the following links to learn about the action listeners:-
1)How to Apply the Textchange event on EditText
2)Counting Chars in EditText Changed Listener
After getting the search keyword go through the list and match the objects with the keywords. Then store the list item in a separate list which matches with the search keyword. After search is finished set the new adapter by using the newly created list.
Best of Luck!