how to declare input date in eclipse android - java

i want input date, but i dont know how to declare date in eclipse android
this my code
EditText txtdate;
and then
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_form_lelang);
txtdate = (EditText)findViewById(R.id.txtdate);
this code my asynctask thread
protected String doInBackground(String... params) {
param.add(new BasicNameValuePair("date", txtdate.getText().toString()));
where im write code declare txtdate (Date) ?

package com.example.lelangifan;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.lelangifan.Daftar;
import com.example.lelangifan.ServiceHandler;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class FormLelang extends Activity implements OnClickListener {
EditText txtjudul;
EditText txtharga;
EditText txtdate;
Button btncreate;
JSONArray tag_besar;
int success = 0;
int cek_username = 0;
AlertDialogManager alert = new AlertDialogManager();
private static String url ="http://172.16.10.14/mobile_lelang/create_lelang.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_form_lelang);
txtjudul = (EditText)findViewById(R.id.txtjudul);
txtharga = (EditText)findViewById(R.id.txtharga);
txtdate = (EditText)findViewById(R.id.txtdate);
btncreate = (Button)findViewById(R.id.btncreate);
btncreate.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.daftar, menu);
return true;
}
public void onClick(View view) {
// TODO Auto-generated method stub
if(view == btncreate){
new createJson().execute();
}
}
class createJson extends AsyncTask<String, String, String>{
Integer form_cek = 0;
#Override
protected void onPreExecute(){
super.onPreExecute();
if(txtjudul.getText().toString() == null)
{
alert.showAlertDialog(FormLelang.this, "Info", "Isi Judul", false);
//T_nama_d.focusSearch(0);
form_cek = 1;
}
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
if(txtjudul.getText().length() == 0)
{
form_cek = 1;
}
else if(txtharga.getText().length() == 0)
{
alert.showAlertDialog(FormLelang.this, "Info", "Harga Kosong", false);
form_cek = 1;
}
else if(txtdate.getText().length() == 0)
{
alert.showAlertDialog(FormLelang.this, "Info", "Isi Limit Date", false);
form_cek = 1;
}
if(form_cek == 0){
//Log.d("Form->",String.valueOf(form_cek));
ServiceHandler sh = new ServiceHandler();
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("judul", txtjudul.getText().toString()));
param.add(new BasicNameValuePair("harga", txtharga.getText().toString()));
param.add(new BasicNameValuePair("date", txtdate.getText().toString()));
//param.add(new BasicNameValuePair("jenis_kelamin", T_jeniskelamin_d.getSelectedItem().toString()));
String jsonstrr = sh.makeServiceCall(url, ServiceHandler.POST,param);
try {
JSONObject jsonobjj = new JSONObject(jsonstrr);
tag_besar = jsonobjj.getJSONArray("data");
for(int j = 0; j < tag_besar.length();j++){
JSONObject cc = tag_besar.getJSONObject(j);
success = cc.getInt("success");
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(String result){
if(form_cek == 0){
if(success == 1){
alert.showAlertDialog(FormLelang.this, "Info", "Data Berhasil Disimpan", true);
Intent setupIntent = new Intent(getApplicationContext(),MainActivity.class);
startActivityForResult(setupIntent, RESULT_OK);
finish();
}
else
{
alert.showAlertDialog(FormLelang.this, "Info", "Data Gagal Disimpan", false);
}
}
}
}
}

Related

passing value from button to listview

This is a flowchart of what I want:
the image above is like a flowchart of what i want to create. i want to have first activity with buttons like 10 or so all will have
case 0:
Intent intent = new Intent(getActivity(), AActivity.class);
intent.putExtra("categoryId", 1);
intent.putExtra("title", Animal);
startActivity(intent);
break;
case 1:
Intent e = new Intent(getActivity(), AActivity.class);
e.putExtra("categoryId", 2);
e.putExtra("title", eletronics);
startActivity(e);
break;
case 2:
Intent f = new Intent(getActivity(), AActivity.class);
f.putExtra("categoryId", 3);
f.putExtra("title", fashion);
startActivity(f);
break;
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
include_once($_SERVER['DOCUMENT_ROOT']."/config/config.php");
$id= $_POST['id'];
// Create connection
$conn = new mysqli($host, $user, $pass, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM comments where comment_id = '$id'" ;
$result = $conn->query($sql);
if ($result->num_rows >0) {
while($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode($tem);
}
} else {
echo "No Results Found.";
}
echo $json;
$conn->close();
}
?>
i need help in creating the second activity that will be in listview that will receive that from php and display it. so if button 1 is click it will fetch all data relating to id 1
my question is how will i implement the second activity which will receive the value fetch the values from mysql and display it as list view
this is the one i used in my app try if you can use it
package com.fruitmarket;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.utils.StorageUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import Config.ConstValue;
import adapters.ProductsAdapter;
import imgLoader.AnimateFirstDisplayListener;
import imgLoader.JSONParser;
import util.ConnectionDetector;
import util.ObjectSerializer;
#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
public class ProductsActivity2 extends ActionBarActivity{
public SharedPreferences settings;
public ConnectionDetector cd;
static ArrayList<HashMap<String, String>> products_array;
ProductsAdapter adapter;
ListView products_listview;
DisplayImageOptions options;
ImageLoaderConfiguration imgconfig;
ProgressDialog dialog;
TextView txtcount;
private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
HashMap<String, String> catMap;
#SuppressWarnings("unchecked")
#Override
protected void onCreate(Bundle savedInstanceState) {
settings = getSharedPreferences(ConstValue.MAIN_PREF, 0);
cd = new ConnectionDetector(getApplicationContext());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_products);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
settings = getSharedPreferences(ConstValue.MAIN_PREF, 0);
cd=new ConnectionDetector(this);
File cacheDir = StorageUtils.getCacheDirectory(this);
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.loading)
.showImageForEmptyUri(R.drawable.loading)
.showImageOnFail(R.drawable.loading)
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.displayer(new SimpleBitmapDisplayer())
.imageScaleType(ImageScaleType.NONE)
.build();
imgconfig = new ImageLoaderConfiguration.Builder(this)
.build();
ImageLoader.getInstance().init(imgconfig);
ArrayList<HashMap<String,String>> categoryArray = new ArrayList<HashMap<String,String>>();
try {
categoryArray = (ArrayList<HashMap<String,String>>) ObjectSerializer.deserialize(settings.getString("categoryname", ObjectSerializer.serialize(new ArrayList<HashMap<String,String>>())));
}catch (IOException e) {
e.printStackTrace();
}
catMap = new HashMap<String, String>();
catMap = categoryArray.get(getIntent().getExtras().getInt("position"));
products_array = new ArrayList<HashMap<String,String>>();
try {
products_array = (ArrayList<HashMap<String,String>>) ObjectSerializer.deserialize(settings.getString("products_"+catMap.get("id"), ObjectSerializer.serialize(new ArrayList<HashMap<String,String>>())));
}catch (IOException e) {
e.printStackTrace();
}
products_listview = (ListView)findViewById(R.id.listView1);
adapter = new ProductsAdapter(getApplicationContext(), products_array);
products_listview.setAdapter(adapter);
TextView txtTitle = (TextView)findViewById(R.id.catname);
txtTitle.setText(catMap.get("name"));
txtcount = (TextView)findViewById(R.id.textcount);
products_listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long id) {
// TODO Auto-generated method stub
try {
settings.edit().putString(getString(R.string.productsActivity),ObjectSerializer.serialize(products_array.get(position))).commit();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent intent = new Intent(ProductsActivity2.this, ProductdetailActivity.class);
intent.putExtra("position", position);
startActivity(intent);
}
});
new loadProductsTask().execute(true);
}
#Override
protected void onNewIntent(Intent intent) {
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
if (!query.equalsIgnoreCase("")) {
//use the query to search your data somehow
new loadProductsTask().execute(true);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.products, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
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) {
Intent intent = new Intent(ProductsActivity2.this,MainActivity.class);
startActivity(intent);
}
else if(id==R.id.action_viewcart){
//Intent intent = new Intent(ProductsActivity.this,ViewcartActivity.class);
//startActivity(intent);
}
else if(id == android.R.id.home){
finish();
}
return super.onOptionsItemSelected(item);
}
public class loadProductsTask extends AsyncTask<Boolean, Void, ArrayList<HashMap<String, String>>> {
JSONParser jParser;
JSONObject json;
String count;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
// TODO Auto-generated method stub
if (result!=null) {
//adapter.notifyDataSetChanged();
}
try {
settings.edit().putString("products_"+catMap.get("id"),ObjectSerializer.serialize(products_array)).commit();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
txtcount.setText(count);
adapter.notifyDataSetChanged();
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(Void... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
#Override
protected void onCancelled(ArrayList<HashMap<String, String>> result) {
// TODO Auto-generated method stub
super.onCancelled(result);
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(
Boolean... params) {
// TODO Auto-generated method stub
try {
jParser = new JSONParser();
if(cd.isConnectingToInternet())
{
String urlstring = ConstValue.JSON_PRODUCTS+"&id="+catMap.get("id");
if (Intent.ACTION_SEARCH.equals(getIntent().getAction())) {
String query = getIntent().getStringExtra(SearchManager.QUERY);
//use the query to search your data somehow
urlstring = urlstring + "&search="+query;
}
json = jParser.getJSONFromUrl(urlstring);
count = json.getString("count");
if (json.has("data")) {
if(json.get("data") instanceof JSONArray){
JSONArray jsonDrList = json.getJSONArray("data");
products_array.clear();
for (int i = 0; i < jsonDrList.length(); i++) {
JSONObject obj = jsonDrList.getJSONObject(i);
put_object(obj);
}
}else if(json.get("data") instanceof JSONObject){
put_object(json.getJSONObject("data"));
}
}
}else
{
Toast.makeText(ProductsActivity2.this,getString(R.string.internetconnection), Toast.LENGTH_LONG).show();
}
jParser = null;
json = null;
} catch (Exception e) {
// TODO: handle exception
return null;
}
return null;
}
public void put_object(JSONObject obj){
HashMap<String, String> map = new HashMap<String, String>();
try {
map.put("id", obj.getString("id"));
map.put("title", obj.getString("title"));
map.put("slug", obj.getString("slug"));
map.put("description", obj.getString("description"));
map.put("image", obj.getString("image"));
map.put("price", obj.getString("price"));
map.put("currency", obj.getString("currency"));
map.put("discount", obj.getString("discount"));
map.put("cod", obj.getString("cod"));
map.put("emi", obj.getString("emi"));
map.put("status", obj.getString("status"));
map.put("gmqty", obj.getString("gmqty"));
map.put("unit", obj.getString("unit"));
map.put("deliverycharge", obj.getString("deliverycharge"));
map.put("tax", obj.getString("tax"));
map.put("category_id", obj.getString("category_id"));
map.put("on_date", obj.getString("on_date"));
map.put("stock", obj.getString("stock"));
map.put("type", obj.getString("type"));
map.put("total_qty_stock", obj.getString("total_qty_stock"));
map.put("consume_qty_stock", obj.getString("consume_qty_stock"));
products_array.add(map);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

How can I compare my Encrypted password from database in android

Here are my Android and PHP codes available. I am able to compare the password and Login successfully if password is in form of normal String. But when I am entering the password in encrypted format I am not able to compare the password value.And therefore not able to Login Successfully.
SignUpActivity.Java
package com.kezinking.nupur.kezinking;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static android.R.attr.id;
/**
* Created by Nupur on 8/2/2016.
*/
public class SignupActivity extends AppCompatActivity {
private static final String TAG ="" ;
TextView link_login;
Button btn_signup;
EditText input_username;
EditText input_email;
EditText input_password;
String username;
String email;
String password;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
link_login = (TextView) findViewById(R.id.link_login);
btn_signup = (Button) findViewById(R.id.btn_signup);
input_username=(EditText) findViewById(R.id.input_username);
input_email=(EditText) findViewById(R.id.input_email);
input_password=(EditText) findViewById(R.id.input_password);
link_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(SignupActivity.this, LoginActivity.class);
startActivity(intent);
SignupActivity.this.getIntent();
}
});
btn_signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
username = input_username.getText().toString();
email= input_email.getText().toString();
password = input_password.getText().toString();
SignUp();
}
});
}
public void SignUp() {
if (!validate()) {
onSignupFailed();
return;
}else{
insert(username,email,password);
}
}
public void insert(final String username, final String email,final String password){
class SendPostReqAsynTask extends AsyncTask<String,Void,String> {
#Override
protected String doInBackground(String... params) {
String paramUsername=params[0];
String paramPassword=params[1];
//String username = etUsername.getText().toString();
//String password = etPassword.getText().toString();
List<NameValuePair> nameValuePairs= new ArrayList<>();
nameValuePairs.add(new BasicNameValuePair("username",username));
nameValuePairs.add(new BasicNameValuePair("email",email));
nameValuePairs.add(new BasicNameValuePair("password",password));
try{
HttpClient httpClient = new DefaultHttpClient();
// HttpGet request = new HttpGet("http://www.example.com");
HttpPost httpPost = new HttpPost("http://kezinking.com/SignUpAndroid");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response= httpClient.execute(httpPost);
HttpEntity entity= response.getEntity();
int i =response.getStatusLine().getStatusCode();
System.out.println(i);
onSignupSuccess();
}catch(ClientProtocolException e){
}catch (IOException e){
}
return "Success";
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
// Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
TextView textViewResult = (TextView) findViewById(R.id.txtResultCheck);
textViewResult.setText("Successfully Registered");
}
}
SendPostReqAsynTask sendPostReqAsynTask=new SendPostReqAsynTask();
sendPostReqAsynTask.execute(username,password);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onSignupSuccess() {
//btn_signup.setEnabled(true);
Intent intent=new Intent(SignupActivity.this,MainActivity.class);
startActivity(intent);
SignupActivity.this.getIntent();
}
public void onSignupFailed() {
Toast.makeText(getBaseContext(), "Failed to Register", Toast.LENGTH_LONG).show();
// btn_signup.setEnabled(true);
}
public boolean validate() {
boolean valid = true;
String username = input_username.getText().toString();
String email = input_email.getText().toString();
String password = input_password.getText().toString();
if (username.isEmpty() || username.length() < 3) {
input_username.setError("at least 3 characters");
valid = false;
} else {
input_username.setError(null);
}
if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
input_email.setError("enter a valid email address");
valid = false;
} else {
input_email.setError(null);
}
if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
input_password.setError("between 4 and 10 alphanumeric characters");
valid = false;
} else {
input_password.setError(null);
}
return valid;
}
}
LoginActivity.Java
package com.kezinking.nupur.kezinking;
import android.animation.ObjectAnimator;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Space;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by Nupur on 8/2/2016.
*/
public class LoginActivity extends AppCompatActivity {
public static final String MY_JSON = "MY_JSON";
private static final String JSON_URL = "http://kezinking.com/AndroidLogin";
EditText input_email, input_password;
Button btn_login, btnContactUs, btnWorkhr, btnDeltime, btnMoneyBack;
TextView link_signup, textViewJSON, txtcheck;
private static Boolean flag = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btn_login = (Button) findViewById(R.id.btn_login);
link_signup = (TextView) findViewById(R.id.link_signup);
input_email = (EditText) findViewById(R.id.input_email);
input_password = (EditText) findViewById(R.id.input_password);
textViewJSON = (TextView) findViewById(R.id.textViewJSON);
// value=(TextView)findViewById(R.id.value);
txtcheck = (TextView) findViewById(R.id.txtcheck);
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
login();
}
});
link_signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(LoginActivity.this, SignupActivity.class);
startActivity(intent);
LoginActivity.this.getIntent();
}
});
}
#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);
}
public void login() {
if (!validate()) {
onLoginFailed();
return;
} else {
getJSON(JSON_URL);
}
}
public void getJSON(String url) {
class GetJSON extends AsyncTask<String, Void, String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(LoginActivity.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 result=null;
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);
String jsonString = textViewJSON.getText().toString();
//String jsonString = "{\"result\":[{\"Vendor_ID\":\"1\",\"username\":\"nupur\",\"password\":\"nupur\"},{\"Vendor_ID\":\"4\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"3\",\"username\":\"nupur\",\"password\":\"1234\"},{\"Vendor_ID\":\"5\",\"username\":\"RAJ\",\"password\":\"RAJ\"},{\"Vendor_ID\":\"6\",\"username\":\"RAJ\",\"password\":\"RAJ\"},{\"Vendor_ID\":\"7\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"8\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"9\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"10\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"11\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"12\",\"username\":\"RAM\",\"password\":\"RAM\"},{\"Vendor_ID\":\"13\",\"username\":\"RAM\",\"password\":\"RAM\"},{\"Vendor_ID\":\"14\",\"username\":\"RAM\",\"password\":\"RAM\"},{\"Vendor_ID\":\"15\",\"username\":\"RAM\",\"password\":\"RAM\"},{\"Vendor_ID\":\"16\",\"username\":\"Nupur\",\"password\":\"Nupur\"},{\"Vendor_ID\":\"17\",\"username\":\"Nupur\",\"password\":\"Nupur\"},{\"Vendor_ID\":\"18\",\"username\":\"Nupur\",\"password\":\"Nupur\"},{\"Vendor_ID\":\"19\",\"username\":\"Nupur\",\"password\":\"Nupur\"},{\"Vendor_ID\":\"20\",\"username\":\"Rohit\",\"password\":\"Rohit\"},{\"Vendor_ID\":\"21\",\"username\":\"RAM\",\"password\":\"RAM\"},{\"Vendor_ID\":\"22\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"23\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"24\",\"username\":\"RAM\",\"password\":\"RAM\"},{\"Vendor_ID\":\"35\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"34\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"33\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"32\",\"username\":\"RAM\",\"password\":\"RAM\"},{\"Vendor_ID\":\"31\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"36\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"37\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"38\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"39\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"40\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"41\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"73\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"43\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"44\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"45\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"46\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"47\",\"username\":\"username\",\"password\":\"password\"},{\"Vendor_ID\":\"74\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"75\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"72\",\"username\":\"Krishna\",\"password\":\"Krishna\"},{\"Vendor_ID\":\"68\",\"username\":\"Honey\",\"password\":\"Honey\"},{\"Vendor_ID\":\"69\",\"username\":\"Ram\",\"password\":\"Ram\"},{\"Vendor_ID\":\"70\",\"username\":\"Ram\",\"password\":\"Ram\"},{\"Vendor_ID\":\"71\",\"username\":\"Ram\",\"password\":\"Ram\"}]}";
//String email = (input_email.getText().toString());
//txtcheck.setText(jsonString);
String email = input_email.getText().toString();
String password = input_password.getText().toString();
// final String myResult = (email) + (password);
String value = (String.valueOf(email + password));
System.out.println(value);
// String value=(input_email.getText().toString()+input_password.getText().toString());
//String input_email = "";
//String input_password = "";
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray result = jsonObject.getJSONArray("result");
//System.out.println("result " + result);
//iterate through json array and check if id is same with your search
//System.out.println("length " + result.length());
for (int i = 0; i < result.length(); i++) {
System.out.println(i);
JSONObject item = result.getJSONObject(i);
String Email = item.getString("email");
String Password = item.getString("password");
//System.out.println("Email from json "+ Email);
//System.out.println("Password from json " + Password);
if (Email.equals(email) && Password.equals(password)) {
System.out.println("Email from json"+ Email);
System.out.println("Password from json" + Password);
flag=true;
onLoginSuccess();
break;
}
}
if(!flag){
onLoginFailed();
}
} catch (JSONException e) {
e.printStackTrace();
}
//here you can show the result
Log.v(this.getClass().getSimpleName(), "email = " + email);
Log.v(this.getClass().getSimpleName(), "password = " + password);
//txtcheck.setText(email);
}
}
GetJSON gj = new GetJSON();
gj.execute(url);
}
#Override
public void onBackPressed() {
// disable going back to the MainActivity
moveTaskToBack(true);
}
public void onLoginSuccess() {
btn_login.setEnabled(true);
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
LoginActivity.this.getIntent();
// finish();
}
public void onLoginFailed() {
Toast.makeText(getBaseContext(), "Login failed", Toast.LENGTH_LONG).show();
// btn_login.setEnabled(true);
}
public boolean validate() {
boolean valid = true;
String email = input_email.getText().toString();
String password = input_password.getText().toString();
if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
input_email.setError("enter a valid email address");
valid = false;
} else {
input_email.setError(null);
}
if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
input_password.setError("between 4 and 10 alphanumeric characters");
valid = false;
} else {
input_password.setError(null);
}
return valid;
}
}
PHP- AndroidLogin.php
<?php
$con=mysqli_connect("localhost","amodbina0106","Amodbina200","kezin_king");
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
?>
<?php
$sql=mysqli_query($con,"SELECT email,password FROM `users` WHERE 1");
$result=array();
while($row=mysqli_fetch_assoc($sql))
{
$result[]=$row;
}
echo json_encode(array("result"=>$result));
?>
PHP-SignUpAndroid.php
<?php
$con=mysqli_connect("localhost","amodbina0106","Amodbina200","kezin_king");
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
echo "Connected successfully";
?>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<table style="width: 100%">
<?php
$username=($_POST['username']);
$email=($_POST['email']);
$password=($_POST['password']);
$encryptedpassword=md5($password);
$sql=mysqli_query($con,"INSERT INTO `kezin_king`.`users` (`user_id`, `username`, `name`, `shop-name`, `password`, `email`, `adr`, `con_no`, `type`, `profile`, `doj`, `banner`, `banner1`, `lat`, `lon`, `email_code`, `activation`) VALUES (NULL, '$username', '', '', '$encryptedpassword', '$email', '', '', '', '', '', '', '', '', '', '', '1')");
$sql=mysqli_query($con,"SELECT name,username,password,email FROM `user` WHERE 1");
while($row=mysqli_fetch_assoc($sql))
{
$username=$row['username'];
$email=$row['email'];
$password=$row['password'];
?>
<tr>
<th><?php echo $username; ?></th>
<th><?php echo $email; ?></th>
<th><?php echo $password; ?></th>
</tr>
<?php }?>
</table>
Please help me.We can do the login if password is Encrypted ?
Thanks in Advance
Error/Output:-
V/GetJSON: email = check#check.com
V/GetJSON: password = check1
I/ViewRootImpl: CPU Rendering VSync enable = true
"LoginFailed"

error return NULL app json_code return NULL

I have a android application news, where I receive data from a server Jons until everything well, the problem is that when I'm in the app and minimize to do something else and when I try to resume where I left off the app comes with NULL data
part
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class ActivityDetailStory extends AppCompatActivity {
int position;
String str_cid, str_cat_id, str_cat_image, str_cat_name, str_title, str_image, str_desc, str_date;
TextView news_title, news_date;
WebView news_desc;
ImageView img_news, img_fav;
DatabaseHandler db;
List<ItemStoryList> arrayOfRingcatItem;
ItemStoryList objAllBean;
final Context context = this;
ProgressBar progressBar;
LinearLayout content;
private AdView mAdView;
private InterstitialAd interstitial;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_story);
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final android.support.v7.app.ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(Constant.CATEGORY_TITLE);
}
//show admob banner ad
mAdView = (AdView) findViewById(R.id.adView);
mAdView.loadAd(new AdRequest.Builder().build());
mAdView.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
}
#Override
public void onAdFailedToLoad(int error) {
mAdView.setVisibility(View.GONE);
}
#Override
public void onAdLeftApplication() {
}
#Override
public void onAdOpened() {
}
#Override
public void onAdLoaded() {
mAdView.setVisibility(View.VISIBLE);
}
});
content = (LinearLayout) findViewById(R.id.content);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
img_fav = (FloatingActionButton) findViewById(R.id.img_fav);
img_news = (ImageView) findViewById(R.id.image);
news_title = (TextView) findViewById(R.id.title);
news_date = (TextView) findViewById(R.id.subtitle);
news_desc = (WebView) findViewById(R.id.desc);
db = new DatabaseHandler(ActivityDetailStory.this);
arrayOfRingcatItem = new ArrayList<ItemStoryList>();
//imageLoader = new ImageLoader(ActivityDetailStory.this);
if (JsonUtils.isNetworkAvailable(ActivityDetailStory.this)) {
new MyTask().execute(Constant.SERVER_URL + "/api.php?nid=" + Constant.NEWS_ITEMID);
MyApplication.getInstance().trackScreenView("Lendo de cara : " + (Constant.CATEGORY_TITLE));
}
else {
Toast.makeText(getApplicationContext(), "Problema com sua Rede de Internet", Toast.LENGTH_SHORT).show();
}
}
private class MyTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... params) {
return JsonUtils.getJSONString(params[0]);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressBar.setVisibility(View.GONE);
content.setVisibility(View.VISIBLE);
if (null == result || result.length() == 0) {
Toast.makeText(getApplicationContext(), "Problema com sua Rede de Internet!", Toast.LENGTH_SHORT).show();
} else {
try {
JSONObject mainJson = new JSONObject(result);
JSONArray jsonArray = mainJson.getJSONArray(Constant.CATEGORY_ARRAY_NAME);
JSONObject objJson = null;
for (int i = 0; i < jsonArray.length(); i++) {
objJson = jsonArray.getJSONObject(i);
ItemStoryList objItem = new ItemStoryList();
objItem.setCId(objJson.getString(Constant.CATEGORY_ITEM_CID));
objItem.setCategoryName(objJson.getString(Constant.CATEGORY_ITEM_NAME));
objItem.setCategoryImage(objJson.getString(Constant.CATEGORY_ITEM_IMAGE));
objItem.setCatId(objJson.getString(Constant.CATEGORY_ITEM_CAT_ID));
objItem.setNewsImage(objJson.getString(Constant.CATEGORY_ITEM_NEWSIMAGE));
objItem.setNewsHeading(objJson.getString(Constant.CATEGORY_ITEM_NEWSHEADING));
objItem.setNewsDescription(objJson.getString(Constant.CATEGORY_ITEM_NEWSDESCRI));
objItem.setNewsDate(objJson.getString(Constant.CATEGORY_ITEM_NEWSDATE));
arrayOfRingcatItem.add(objItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
setAdapterToListview();
}
}
}
public void setAdapterToListview() {
objAllBean = arrayOfRingcatItem.get(0);
str_cid = objAllBean.getCId();
str_cat_name = objAllBean.getCategoryName();
str_cat_image = objAllBean.getCategoryImage();
str_cat_id = objAllBean.getCatId();
str_title = objAllBean.getNewsHeading();
str_desc = objAllBean.getNewsDescription();
str_image = objAllBean.getNewsImage();
str_date = objAllBean.getNewsDate();
news_title.setText(str_title);
news_date.setText(str_date);
news_desc.setBackgroundColor(Color.parseColor("#FFFFFF"));
news_desc.setFocusableInTouchMode(false);
news_desc.setFocusable(false);
news_desc.getSettings().setDefaultTextEncodingName("UTF-8");
WebSettings webSettings = news_desc.getSettings();
Resources res = getResources();
int fontSize = res.getInteger(R.integer.font_size);
webSettings.setDefaultFontSize(fontSize);
String mimeType = "text/html; charset=UTF-8";
String encoding = "utf-8";
String htmlText = str_desc;
String text = "<html><head><style type=\"text/css\">#font-face {font-family: MyFont;src: url(\"file:///android_asset/Roboto-Light.ttf\")}body {font-family: MyFont;font-size: medium; color: #525252;}</style></head><body>"
+ htmlText + "</body></html>";
news_desc.loadData(text, mimeType, encoding);
List<Pojo> pojolist = db.getFavRow(str_cat_id);
if (pojolist.size() == 0) {
img_fav.setImageResource(R.drawable.ic_bookmark_outline);
} else {
if (pojolist.get(0).getCatId().equals(str_cat_id))
;
{
img_fav.setImageResource(R.drawable.ic_bookmark_white);
}
}
img_fav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
List<Pojo> pojolist = db.getFavRow(str_cat_id);
if (pojolist.size() == 0) {
db.AddtoFavorite(new Pojo(str_cat_id, str_cid, str_cat_name, str_title, str_image, str_desc, str_date));
Toast.makeText(getApplicationContext(), "Leitura Marcada", Toast.LENGTH_SHORT).show();
img_fav.setImageResource(R.drawable.ic_bookmark_white);
interstitial = new InterstitialAd(ActivityDetailStory.this);
interstitial.setAdUnitId(getString(R.string.admob_interstitial_id));
AdRequest adRequest = new AdRequest.Builder().build();
interstitial.loadAd(adRequest);
interstitial.setAdListener(new AdListener() {
public void onAdLoaded() {
if (interstitial.isLoaded()) {
interstitial.show();
}
}
});
} else {
if (pojolist.get(0).getCatId().equals(str_cat_id)) {
db.RemoveFav(new Pojo(str_cat_id));
Toast.makeText(getApplicationContext(), "Leitura desmarcada!", Toast.LENGTH_SHORT).show();
img_fav.setImageResource(R.drawable.ic_bookmark_outline);
}
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_story, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
onBackPressed();
break;
case R.id.menu_share:
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Estou lendo vários livro com esse app estou adorando, baixe já, Recomendo "+"https://play.google.com/store/apps/details?id="+getPackageName());
sendIntent.setType("text/plain");
startActivity(sendIntent);
break;
default:
return super.onOptionsItemSelected(menuItem);
}
return true;
}
#Override
protected void onPause() {
// mAdView.pause();
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
//mAdView.resume();
}
#Override
protected void onDestroy() {
//mAdView.destroy();
super.onDestroy();
}
}
what you get in the log is, the more I believe that it has nothing to do.
03-21 18:58:20.032 1342-1342/? E/dalvikvm: Could not find class 'android.app.AppOpsManager', referenced from method com.google.android.gms.common.ou.a
03-21 18:58:20.165 1342-1342/? E/dalvikvm: Could not find class 'android.app.AppOpsManager', referenced from method com.google.android.gms.common.j.a
03-21 18:58:20.404 1342-1342/? E/com.parse.PushService: The Parse push service cannot start because Parse.initialize has not yet been called. If you call Parse.initialize from an Activity's onCreate, that call should instead be in the Application.onCreate. Be sure your Application class is registered in your AndroidManifest.xml with the android:name property of your <application> tag.
03-21 18:58:20.604 1416-1416/? E/dalvikvm: Could not find class 'android.app.AppOpsManager', referenced from method com.google.android.gms.common.GooglePlayServicesUtil.zza
03-21 18:58:20.777 1284-1445/? E/sqlite3_android: CDF_MAX_DIGIT_MATCH = 100
03-21 18:58:20.777 1284-1445/? E/sqlite3_android: CDF_MIN_DIGIT_MATCH = 7
03-21 18:58:21.014 1416-1478/? E/sqlite3_android: CDF_MAX_DIGIT_MATCH = 100
03-21 18:58:21.014 1416-1478/? E/sqlite3_android: CDF_MIN_DIGIT_MATCH = 7
How do I not return NULL
Thank you

Error org.json.JSONException: Value <html><head><title> Error of type java.lang.String cannot be converted to JSONObject

I have a Android app about Public Transportation, and I have a PHP script that connects to mySQL database. This is the main.java
package com.chera.trans;
import com.chera.trans.R;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
public class Main extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.traseu2:
Intent traseu2 = new Intent(this, Traseu2.class);
this.startActivity(traseu2);
break;
case R.id.traseu401:
Intent traseu401 = new Intent(this, Traseu401.class);
this.startActivity(traseu401);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
}
And this is the code for Traseu2.java
package com.chera.trans;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.chera.trans.R;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class Traseu2 extends Activity {
private String jsonResult;
private String url = "http://transploiesti.tk/2.php";
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.traseu2);
listView = (ListView) findViewById(R.id.listView1);
accessWebService();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.traseu2:
Intent traseu2 = new Intent(this, Traseu2.class);
this.startActivity(traseu2);
break;
case R.id.traseu401:
Intent traseu401 = new Intent(this, Traseu401.class);
this.startActivity(traseu401);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrwaer();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void ListDrwaer() {
List<Map<String, String>> employeeList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("traseudoi");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("Statie");
String number = jsonChildNode.optString("Oraplecare");
String outPut = "Autobuzul pleaca din " + name + " la ora " + number;
employeeList.add(createEmployee("employees", outPut));
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList,
android.R.layout.simple_list_item_1,
new String[] { "employees" }, new int[] { android.R.id.text1 });
listView.setAdapter(simpleAdapter);
}
private HashMap<String, String> createEmployee(String name, String number) {
HashMap<String, String> employeeNameNo = new HashMap<String, String>();
employeeNameNo.put(name, number);
return employeeNameNo;
}
}
` Why I receive this error when I m running the app? Thanks!
HTML is not JSON, and it can not be parsed into JSONObjects. The top answer for org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject is pretty good at explaining this further.

ListViewActivity with Custom Adapter doesn' t work

Dear Stackoverflow Comunitiy,
I'd like to have a ListView getting filled by an BackgroundTask.
This is my actual Code
HomeActivity:
package com.example.instaemgnew;
import java.util.ArrayList;
import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import com.example.instaemgnew.classes.Beitrag;
import com.example.instaemgnew.classes.beitragLoader;
import com.example.instaemgnew.classes.listViewHomeActivitiyAdapter;
public class HomeActivity extends ListActivity {
listViewHomeActivitiyAdapter adapter;
ArrayList<Beitrag> beitraege = new ArrayList<Beitrag>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
adapter = new listViewHomeActivitiyAdapter(this, beitraege);
setListAdapter(adapter);
Log.e("TestPoint 1", "Adapter Set");
new beitragLoader(this).execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_home, menu);
return true;
}
public void addToListView(Beitrag toAddBeitrag){
beitraege.add(toAddBeitrag);
adapter.notifyDataSetChanged();
}
}
BackgroundTask:
package com.example.instaemgnew.classes;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.instaemgnew.HomeActivity;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.widget.ArrayAdapter;
public class beitragLoader extends AsyncTask<String, String, String>{
//Array List für die Beiträge
ArrayList<Beitrag> beitraege;
//User Daten
/*mail = userManager.getMail();
grade = String.valueOf(userManager.getGrade());
school = userManager.getSchool();*/
String mail = "simon-frey#gmx.de";
String grade = String.valueOf(334);
String school = "EMG";
//JSONParser
JSONParser jsonParser = new JSONParser();
//ArrayList mit Beitrag Objekten
ArrayList<Beitrag> beitraegeList;
// Onlinedaten
private static final String SERVER_URL = "http://yooui.de/InstaEMGTest/";
private static final String PASSWORD = "8615daf406f7e2b313494f0240";
//Context
private final HomeActivity homeActivity;
//Konstruktor
public beitragLoader(HomeActivity homeActivity){
this.homeActivity = homeActivity;
Log.e("TestPoint 2", "Created beitragLoader");
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//TODO: Test for InternetConnection
Log.e("TestPoint 3", "PreExectute");
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
beitraegeList = new ArrayList<Beitrag>();
String SQLUrl = SERVER_URL + "testBeiträgeAbrufen.php";
String token = getMD5Hash("password" + "data");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("token", token));
//TODO: params.add(new BasicNameValuePair("page", skipBeitraege))
params.add(new BasicNameValuePair("grade", grade));
params.add(new BasicNameValuePair("school", school));
JSONObject json = jsonParser.makeHttpRequest(SQLUrl, "GET", params);
if (json == null) {
// Server offline
}
Log.e("TestPoint 3,5", "FetchedJSON");
try {
JSONArray beitraege = json.getJSONArray("beitraege");
// looping through All Products
for (int i = 0; i < beitraege.length(); i++) {
Beitrag tempBeitrag = null;
Log.e("TestPoint 3,6", "StartLoop");
JSONObject c = beitraege.getJSONObject(i);
//HDImagesURLList ArrayList
ArrayList<String> HDImagesURLList = new ArrayList<String>();
// Storing each json item in variable
String id = c.getString("ID");
String url = c.getString("url");
String titel = c.getString("titel");
String tags = c.getString("tags");
String onlineDate = c.getString("onlineDate");
Log.e("TestPoint 3,7", "Stored JSON Items");
//Fetching previewImage
try {
Log.e("TestPoint 3,8", "TryImageDownload");
InputStream in = new java.net.URL(url).openStream();
String fileName = "InstaEMG" + String.valueOf(System.currentTimeMillis())+".jpg";
Log.e("imageUri", url);
Log.e("fileName", fileName);
FileOutputStream fileOutput = new FileOutputStream(new File(Environment.getExternalStorageDirectory(),fileName));
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = in.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
Log.e("File Output", String.valueOf(bufferLength));
}
//Fill HDImagesURLList
//TODO
// creating newBeitrag
tempBeitrag = new Beitrag(Integer.parseInt(id), titel, onlineDate, fileName, HDImagesURLList);
// adding Beitrag to ArrayList
beitraegeList.add(tempBeitrag);
Log.e("TestPoint 4", "NewBeitragSet");
} catch (MalformedURLException e) {
Log.e("Exceptrion", "URL Exception");
} catch (IOException e) {
Log.e("Exceptrion", "IO Exception");
}
homeActivity.addToListView(tempBeitrag);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} return null;
}
/**
* After completing background Safe to MainActivity
* **/
protected void onPostExecute() {
Log.e("TestPoint 5", "PostExecutre");
// homeActivity.updateListView(beitraegeList);
}
/**
* Methode zum Errechnen eines MD5Hashs
*
* #param string
* String welcher kodiert werden soll
* #return MD5 Hash des Strings, bei Fehler der ursprüngliche String.
*/
private String getMD5Hash(String string) {
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(string.getBytes());
byte[] result = md5.digest();
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < result.length; i++) {
if ((0xff & result[i]) < 0x10) {
hexString.append("0" + Integer.toHexString((0xFF & result[i])));
} else {
hexString.append(Integer.toHexString(0xFF & result[i]));
}
}
string = hexString.toString();
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
}
return string;
};
}
and the BaseAdapter:
package com.example.instaemgnew.classes;
import java.util.ArrayList;
import com.example.instaemgnew.R;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class listViewHomeActivitiyAdapter extends BaseAdapter {
private final Context context;
private ArrayList<Beitrag> beitraege;
private final LayoutInflater layoutInflater;
public listViewHomeActivitiyAdapter(Context context, ArrayList<Beitrag> beitraege) {
super();
this.beitraege = beitraege;
this.context = context;
this.layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
//Allgemeien Layout Vorgaben
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.single_beitrag_row_layout, parent, false);
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.single_beitrag_row_layout, null);
}
//getViews
TextView titelView = (TextView) rowView.findViewById(R.id.beitragTitel);
ImageView beitragImageView = (ImageView) rowView.findViewById(R.id.beitragImg);
/*
* TODO: Tags anzeigen und suchen lassen (Wunschfunktion)
* TextView tagsView = (TextView) rowView.findViewById(R.id.beitragTags);
*/
//setTitel From Object
titelView.setText(beitraege.get(position).getTitel());
//setPreviewImage From Object
beitragImageView.setImageBitmap(beitraege.get(position).getPreviewImage());
//setOnClickListener on PreviewImage for PopOutGallery
beitragImageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//TODO: PopOut Gallery
}
});
return rowView;
}
#Override
public int getCount() {
return beitraege.size();
}
#Override
public Object getItem(int position) {
return beitraege.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
}
In my opinion the Bug have to be in the BaseAdapter, but I don't know where it could be.
Sincerly and thankful,
Simon
To fill listView in doInBackground you need to use Handler, or runOnUiThread, because this is not UI thread.
homeActivity.runOnUiThread(new Runnable()
{
public void run()
{
homeActivity.addToListView(tempBeitrag);
}});
adapter = new listViewHomeActivitiyAdapter(this, beitraege);
beitraege is not populated with any data.
Edit:
Instead of calling this from doInbackground. Use a Interface as a call back to the activity and then populate listview.
public void addToListView(Beitrag toAddBeitrag){
beitraege.add(toAddBeitrag);
adapter.notifyDataSetChanged();
}
How do I return a boolean from AsyncTask?
Instead of boolen value its arraylist in your case.
Then use the below and set the adapter your listview
adapter = new listViewHomeActivitiyAdapter(this, beitraege);

Categories

Resources