Debugging Android App communicating with Servlet on real device - java

So the scenario is I am trying to debug a simple application on my real device.I am using eclipse to make the application.
Now my application is communicating with a servlet which is on Server and application is running very smoothly in genymotion emulator(not using the emulator provided by eclipse). But when I try to run it in my device it is working perfectly till one activity class,but application is crashing on second activity.
So, after so many searches I am posting this question here. Hope I can find out any solution for this.
This is my Second Activity:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.success);
Intent objIntent = getIntent();
s2 = objIntent.getStringExtra("repname");
findViewsById();
submit.setOnClickListener(this);
}
private void findViewsById() {
submit = (Button) findViewById(R.id.submit);
headerText = (TextView) findViewById(R.id.tv1);
headerText.setVisibility(View.INVISIBLE);
submit2 = (Button) findViewById(R.id.secondSubmit);
submit2.setVisibility(View.INVISIBLE);
t1= (TextView) findViewById(R.id.tvexample1);
t2= (TextView) findViewById(R.id.tvexample2);
submit2.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
//DO SOMETHING! {RUN SOME FUNCTION ... DO CHECKS... ETC}
lviewAdapter.clear();
lviewAdapter.notifyDataSetChanged();
Calendar cal = Calendar.getInstance();
System.out.println("what is from calendar"+cal);
Date currentLocalTime = cal.getTime();
//System.out.println("what is from CurrentLocalTime"+currentLocalTime);
DateFormat date = new SimpleDateFormat("yyyy-MM-dd");
date.setTimeZone(TimeZone.getTimeZone("GMT"));
//System.out.println("what is from date"+date);
String localTime = date.format(currentLocalTime);
//localTime = "2014-08-26";
System.out.println("and result is == " + localTime);
pb.setVisibility(View.VISIBLE);
new MyAsyncTask().execute(localTime,s2);
}
});
pb=(ProgressBar)findViewById(R.id.progressBar1);
pb.setVisibility(View.GONE);
c=this;
}
public void onClick(View view) {
Log.d("1:", "in the onclick");
Calendar cal = Calendar.getInstance();
System.out.println("what is from calendar"+cal);
Date currentLocalTime = cal.getTime();
//System.out.println("what is from CurrentLocalTime"+currentLocalTime);
DateFormat date = new SimpleDateFormat("yyyy-MM-dd");
date.setTimeZone(TimeZone.getTimeZone("GMT"));
//System.out.println("what is from date"+date);
String localTime = date.format(currentLocalTime);
//localTime = "2014-08-26";
System.out.println("and result is == " + localTime);
pb.setVisibility(View.VISIBLE);
new MyAsyncTask().execute(localTime,s2);
}
// #Override
// public void onBackPressed() {
// Log.d("CDA", "onBackPressed Called");
// Intent setIntent = new Intent(Intent.ACTION_MAIN);
// setIntent.addCategory(Intent.CATEGORY_HOME);
// setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// startActivity(setIntent);
// }
private class MyAsyncTask extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
Log.d("tag1","in do in ");
String s=postData(params);
Log.d("tag2","in do in SSS ");
//Printing this 5 th
Log.d("what is s",s);
return s;
}
protected void onPostExecute(String result){
Log.d("on post ","on post execute");
pb.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(),"Appointment Displayed", Toast.LENGTH_SHORT).show();
//Log.d("tag",result);
init(result);
submit.setVisibility(View.GONE);
headerText.setVisibility(View.VISIBLE);
submit2.setVisibility(View.VISIBLE);
}
}
protected void onProgressUpdate(Integer... progress){
pb.setProgress(progress[0]);
}
public String postData(String valueIWantToSend[]) {
String origresponseText="";
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("CurrentDate",valueIWantToSend[0]));
nameValuePairs.add(new BasicNameValuePair("repname", valueIWantToSend[1]));
System.out.println("CurrentDate"+valueIWantToSend[0]);
System.out.println("username"+valueIWantToSend[1]);
exampleString1= valueIWantToSend[0];
exampleString2= valueIWantToSend[1];
HttpClient httpclient = new DefaultHttpClient();
HttpParams params = httpclient.getParams();
HttpConnectionParams.setConnectionTimeout(httpclient.getParams(),10000000);
//httppost = new HttpPost("http://192.168.56.1:8080/First/Hello");
httppost = new HttpPost("http://203.199.134.131:8080/First/Hello");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
/* execute */
HttpResponse response = httpclient.execute(httppost);
System.out.println("response from servlet"+response.toString());
origresponseText=readContent(response);
Log.d("response", origresponseText);
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
}
catch (IOException e) {
// TODO Auto-generated catch block
}
//removing unwated "" and other special symbols from response
String responseText = origresponseText.substring(1,origresponseText.length() -2 );
Log.d("Response tag", responseText);
return responseText;
}
// }
String readContent(HttpResponse response)
{
String text = "";
InputStream in =null;
try {
in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
//Log.d("", line);
sb.append(line + "\n");
//Printing this first
// Log.d("", line);
// Log.e("TAGpppp", ">>>>>PRINTING<<<<<");
// Log.e("TAGiiii", in.toString());
}
text = sb.toString();
Log.d("TEXT", text);
}
catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
in.close();
} catch (Exception ex) {
}
}
return text;
}
#SuppressWarnings("deprecation")
public void init(String result) {
System.out.println(result);
t1.setText(exampleString1);
t2.setText(exampleString2);
String response= result + "}";
System.out.println(response);
try {
JSONObject jsonArray = new JSONObject(response);
System.out.println("1:"+jsonArray);
//ArrayList obj1 = new ArrayList();
JSONArray obj1 = jsonArray.getJSONArray("get");
System.out.println("1:"+obj1);
for (int i = 0; i < obj1.length(); i++) {
System.out.println("Length of array"+obj1.length());
JSONObject results = obj1.getJSONObject(i);
System.out.println("2:"+results);
String pcode= results.getString("ProspCustCode");
System.out.println("Prospect code"+pcode);
String date= results.getString("FollowUpDate");
System.out.println("FollowUpDate"+date);
String time= results.getString("FollowUpTime");
System.out.println("FollowUpTime"+time);
String status= results.getString("Status");
System.out.println("Status"+status);
String ftype= results.getString("FollowUpType");
System.out.println("FollowUpType"+ftype);
String ntime= results.getString("NextFollowUpTime");
System.out.println("NextFollowUpTime"+ntime);
String cname= results.getString("ContactPerson");
System.out.println("ContactPerson"+cname);
String desig= results.getString("Designation");
System.out.println("Designation"+desig);
String com= results.getString("Comments");
System.out.println("Comments"+com);
String spoke= results.getString("SpokenTo");
System.out.println("SpokenTo"+spoke);
insertdata(pcode,date,time,status,ftype,ntime,cname,desig,com,spoke);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void insertdata(String PROSPCUSTCODE, String DATE, String TIME,
String STATUS, String FOLLOWUPTYPE, String NEXTFOLLOWUPTIME, String NAME,
String DESIGNATION, String COMMENTS, String SPOKENTO) {
HashMap<String, String> queryValues = new HashMap<String, String>();
queryValues.put("ProspCustCode", PROSPCUSTCODE);
queryValues.put("Date", DATE);
queryValues.put("Time", TIME);
queryValues.put("Status", STATUS);
queryValues.put("FollowUpType", FOLLOWUPTYPE);
queryValues.put("NextFollowUpTime", NEXTFOLLOWUPTIME);
queryValues.put("Name", NAME);
queryValues.put("Designation", DESIGNATION);
queryValues.put("Comments", COMMENTS);
queryValues.put("SpokenTo", SPOKENTO);
controller.insertDeails(queryValues);
//this.callHomeActivity(view);
DBController dbHelper = new DBController(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor cursor = newDB.rawQuery("SELECT * FROM TempFollowUpDetails", null);
if (cursor != null ) {
if (cursor.moveToFirst()) {
do {
System.out.println(cursor.getColumnIndex("ProspCustCode"));
//String ProspCustCode = c.getString(c.getColumnIndex("ProsCustCode"));
String Date = cursor.getString(cursor.getColumnIndex("Date"));
String Time = cursor.getString(cursor.getColumnIndex("Time"));
String Status = cursor.getString(cursor.getColumnIndex("Status"));
String NextFollowUpTime = cursor.getString(cursor.getColumnIndex("NextFollowUpTime"));
Name = cursor.getString(cursor.getColumnIndex("Name"));
System.out.println(cursor.getString(cursor.getColumnIndex("Name")));
String Designation = cursor.getString(cursor.getColumnIndex("Designation"));
String Comments = cursor.getString(cursor.getColumnIndex("Comments"));
String SpokenTo = cursor.getString(cursor.getColumnIndex("SpokenTo"));
String Id = cursor.getString(cursor.getColumnIndex("Id"));
//ProspCustCodeArray.add(ProspCustCode);
DateArray.add(Date);
TimeArray.add(Time);
StatusArray.add(Status);
NextFollowUpTimeArray.add(NextFollowUpTime);
NameArray.add(Name);
DesignationArray.add(Designation);
CommentsArray.add(Comments);
SpokenToArray.add(SpokenTo);
IdArray.add(Id);
}while (cursor.moveToNext());
}
displaylist(IdArray,NameArray);
}
System.out.println("Elements of name array"+NameArray);
System.out.println("Elements of name array"+DateArray);
System.out.println("Elements of name array"+TimeArray);
System.out.println("Elements of name array"+DesignationArray);
System.out.println("Elements of name array"+CommentsArray);
System.out.println("Elements of name array"+IdArray);
//............. For normal listview
}
private void displaylist(ArrayList<String> idArray2,
ArrayList<String> nameArray2) {
// TODO Auto-generated method stub
listView = (ListView) findViewById(R.id.listViewAnimals);
lviewAdapter = new ListCustomAdapter(this, idArray2, nameArray2);
System.out.println("adapter => "+lviewAdapter.getCount());
listView.setAdapter(this.lviewAdapter);
controller.deleteDetails(null);
//... start appointments details activity to show the details on item click listener
this.listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View viewClicked, int position, long id) {
TextView tv1 =(TextView)viewClicked.findViewById(R.id.lblListItem);
Intent intent = new Intent(Success.this, AppointmentDetails.class);
intent.putExtra("name", tv1.getText().toString());
startActivity(intent);
}
}); }
}
This is what my Log cat shows when asynctask is satrting after button click:
D/1:(15416): in the onclick
I/System.out(15416): what is from calendarjava.util.GregorianCalendar[time=1409392501700,areFieldsSet=true,lenient=true,zone=Asia/Calcutta,firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2014,MONTH=7,WEEK_OF_YEAR=35,WEEK_OF_MONTH=5,DAY_OF_MONTH=30,DAY_OF_YEAR=242,DAY_OF_WEEK=7,DAY_OF_WEEK_IN_MONTH=5,AM_PM=1,HOUR=3,HOUR_OF_DAY=15,MINUTE=25,SECOND=1,MILLISECOND=700,ZONE_OFFSET=19800000,DST_OFFSET=0]
I/System.out(15416): and result is == 2014-08-26
D/tag1(15416): in do in
I/System.out(15416): CurrentDate2014-08-26
I/System.out(15416): usernameaditi
I/System.out(15416): [socket][1] connection /203.199.134.131:8080;LocalPort=36598(10000000)
I/System.out(15416): [CDS]connect[/203.199.134.131:8080] tm:10000 D/Posix(15416): [Posix_connect Debug]Process com.example.simplehttpgetservlet :8080
I/System.out(22364): [socket][/192.168.2.73:45340] connected
I/System.out(15416): [CDS]rx timeout:0
W/System.err(15416): rto value is too small
I/System.out(15416): >doSendRequest
I/System.out(15416): <doSendRequest
I/System.out(15416): response from servletorg.apache.http.message.BasicHttpResponse#423611d8

If you use a real device you need to use the real IP of the server. Keep also in mind to open the required ports for your local network and connect your mobile with your local network via WiFi.
I'm not very familar with the secutity of servlets check also that you can connect to the server with a second computer too. (Depending on your configuration it is possible that you cannot access the server from outside of "localhost")

Related

String time passed from AsyncTask class variable not converting into date object in android but it works fine when i hard code the sting

String time passed from AsyncTask class variable not converting into date object in android but it works fine when i hard code the string.
public class Main2Activity extends AppCompatActivity {
String getdate, getday, gethijri, gettimezone, getfajr, getsunrise, getduhr, getasr, getsunset, getmaghrib, getisha, getimsak;
public static final String inputFormat = "hh:mm";
SimpleDateFormat inputParser = new SimpleDateFormat(inputFormat);
String compareFajrOne = "";
String compareFajrTwo = "";
private Date date;
private Date dateComparefajrOne;
private Date dateComparefajrTwo;
private Date dateCompareishaTwo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dailynamazrecord);
Button fajrofer = (Button) findViewById(R.id.fajrada);
final boolean[] ispressed = {false};
Calendar now = Calendar.getInstance();
final int hour = now.get(Calendar.HOUR);
final int minute = now.get(Calendar.MINUTE);
date = parseDateeb(Integer.toString(hour)+":"+ Integer.toString(minute));
dateComparefajrOne = parseDateeb(compareFajrOne);
dateComparefajrTwo = parseDateeb(compareFajrTwo);
fajrofer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(mContext, compareFajrOne+"\n"+compareFajrTwo+"\n"+dateComparefajrOne+"\n"+date+"\n"+dateComparefajrTwo, Toast.LENGTH_LONG).show();
if ( dateComparefajrOne.before(date)&& dateComparefajrTwo.after(date)) {
if (ispressed[0]) {
fajrofer.setBackgroundResource(R.drawable.namazoffered);
} else {
fajrofer.setBackgroundResource(R.drawable.ofeer);
}
ispressed[0] = !ispressed[0];
} else {
if (p != null)
showPopup(Main2Activity.this, p);
}
}
});
public class FectchDetails2 extends AsyncTask<String, String, String> {
String data = "";
#Override
protected String doInBackground(String... params) {
URL url = null;
try {
url = new URL("http://api.aladhan.com/v1/timingsByCity?city=Karachi&country=Pakistan&method=8");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while (line != null) {
line = bufferedReader.readLine();
data = data + line;
}
JSONObject json = new JSONObject(data);
JSONObject gtimings=json2.getJSONObject("timings");
getfajr = gtimings.getString("Fajr");
getsunrise = gtimings.getString("Sunrise");
getduhr = gtimings.getString("Dhuhr");
getasr = gtimings.getString("Asr");
getsunset = gtimings.getString("Sunset");
getmaghrib = gtimings.getString("Maghrib");
getisha = gtimings.getString("Isha");
getimsak = gtimings.getString("Imsak");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
compareStringOne=getfajr.toString();
compareStringTwo=getsunrise.toString();
}
}
private Date parseDateeb(String date) {
try {
return inputParser.parse(date);
} catch (java.text.ParseException e) {
return new Date(0);
}
}
}
String time passed from AsyncTask class variable not converting into date object in android but it works fine when i hard code the sting.
like:
String compareFajrOne = "05:18";
String compareFajrTwo = "06:40";
Kindly guide me i just want to check that current time is in the range of given times

Android Database with MySQL Where Clause

I'm new in Android Programming, and I'm stuck in a middle of SQL query with Where condition. I want to store my data from database into an arraylist. But my script's always fail with Error message. Anyone have a clue? Thanks before
SearchActivity.java
public class SearchActivity extends Activity {
private RadioGroup radiosexGroup;
private RadioButton radiosexButton;
public SeekBar seekBar;
public ArrayList<detailKosan> listKosan = new ArrayList<>();
int progress;
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://192.168.1.133/php_kukelkos/search_kosan.php";
// JSON Node names
private static final String TAG_KOSAN = "arrayKosan";
private static final String TAG_ID = "id";
private static final String TAG_NAMAKOS = "namaKosan";
private static final String TAG_ALAMAT = "alamat";
private static final String TAG_SEX = "gender";
private static final String TAG_TLP = "tlp";
private static final String TAG_HARGA = "harga";
private static final String TAG_KAMAR = "jmlKamar";
private static final String TAG_FASILITAS = "fasilitas";
private static final String TAG_KET = "keterangan";
private static final String TAG_LAT = "lat";
private static final String TAG_LNG = "lng";
// contacts JSONArray
JSONArray arrayKosan = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
textView.setText("Rp 0 - Rp 0");
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progresValue, boolean fromUser) {
progress = progresValue * 500000;
textView.setText("Rp 0 - Rp " + progress);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
textView.setText("Rp 0 - Rp " + progress);
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
//Fungsi Button Search
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
searchKosan();
Intent menuSearch = new Intent(SearchActivity.this, ListKosanActivity.class);
startActivity(menuSearch);
finish();
}
});
public void searchKosan (){
int selected = radiosexGroup.getCheckedRadioButtonId();
radiosexButton = (RadioButton) findViewById(selected);
String buttonradio = radiosexButton.getText().toString();
String msg = "";
String keyval[][]= {{"harga", String.valueOf(progress)},{"gender", buttonradio}};
AsyncTask<String, Void, String> asycn = new myAsyncData(SearchActivity.this, keyval, "Loading...");
asycn.execute(url);
String data = "";
boolean state = false;
try {
JSONObject jobj = null;
try {
data = asycn.get().toString();
} catch (ExecutionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
jobj = new JSONObject(data);
msg = jobj.getString("message").toString();
state = jobj.getBoolean("state");
// Getting JSON Array node
arrayKosan = jobj.getJSONArray(TAG_KOSAN);
/**
* Updating parsed JSON data into Arraylist_detail
**/
for (int i = 0; i < arrayKosan.length(); i++) {
try {
JSONObject c = arrayKosan.getJSONObject(i);
int id = Integer.parseInt(TAG_ID);
String namaKosan = c.getString(TAG_NAMAKOS);
String alamat = c.getString(TAG_ALAMAT);
String sex = c.getString(TAG_SEX);
String tlp = c.getString(TAG_TLP);
int harga = c.getInt(TAG_HARGA);
String kamar = c.getString(TAG_KAMAR);
String fasilitas = c.getString(TAG_FASILITAS);
String ket = c.getString(TAG_KET);
String lat = c.getString(TAG_LAT);
Double latt = Double.parseDouble(lat);
String lng = c.getString(TAG_LNG);
Double lngg = Double.parseDouble(lng);
LatLng PosisiMarker = new LatLng(latt, lngg);
listKosan.add(new detailKosan(id, namaKosan, alamat, sex, tlp, harga, kamar, fasilitas, ket, latt, lngg));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String title = (!state) ? "Error" : "Success";
if(title.equals("Success")) {
Toast.makeText(getApplicationContext(), msg , Toast.LENGTH_LONG).show();
finish();
Intent i = new Intent(SearchActivity.this, ListKosanActivity.class);
startActivity(i);
}
else {
AlertDialog.Builder b = new AlertDialog.Builder(SearchActivity.this);
b.setTitle(title);
b.setMessage(msg);
b.setNegativeButton("Dismiss", null);
AlertDialog a = b.create();
a.show();
}
}
}
And this is my .php file
<?php
if ($_POST) {
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
$harga = $_POST["harga"];
$gender = $_POST["gender"];
$fasilitas = $_POST["fasilitas"];
if(!empty($harga)&&!empty($gender)) {
$ins= mysql_query("SELECT * from tbkosan where harga <='".$harga."' and gender = '".$gender"'");
if (mysql_num_rows($ins> 0) {
$response["state"] = true;
$response["message"] = "Success";
$response["arrayKosan"] = array();
while ($row = mysql_fetch_array($ins)) {
// temp user array
$dataa= array();
$dataa["id"] = $row["id"];
$dataa["namaKosan"] = $row["namaKosan"];
$dataa["alamat"] = $row["alamat"];
$dataa["gender"] = $row["gender"];
$dataa["tlp"] = $row["tlp"];
$dataa["harga"] = $row["harga"];
$dataa["jmlKamar"] = $row["jmlKamar"];
$dataa["fasilitas"] = $row["fasilitas"];
$dataa["keterangan"] = $row["keterangan"];
$dataa["lat"] = $row["lat"];
$dataa["lng"] = $row["lng"];
// push single product into final response array
array_push($result["arrayKosan"], $dataa);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
}
else {
$response["success"] = 0;
$response["message"] = "Data tidak ada";
}
}
else {
$response["success"] = 0;
$response["message"] = "Harap isi data search terlebih dulu!";
echo json_encode($result);
}
}
?>
and this is my ServiceHandler.java
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
and the result is :
alert box with no message, and dissmiss button (sorry i cant post a pic hehe)
mysql_query("SELECT * from tbkosan where harga <='$harga' and gender='$gender'");
I had the same problem AS THIS one of yours i have chosen to use volley library on android part where it helped me to pass input variable to php where clause
refer to this post and check the answer:
How to parse multiple rows with jsonOject
or follow the followithing tutorial watch function called function StoreUserInfo and refer to second part to activity called RegisterActivity.java these can help you to fetch using where clause:
https://www.androidtutorialpoint.com/androidwithphp/android-login-and-registration-with-php-mysql/

JSON parsing android

I need advice about my code.
I'm trying to parse a JSON array generated by the PHP function json_encode().
My json:
{"data": [{"streamer":"froggen","yt_length":"25078"},{"streamer":"wingsofdeath","yt_length":"8979"},{"streamer":"guardsmanbob","yt_length":"4790"},{"streamer":"kaostv","yt_length":"4626"},{"streamer":"kungentv","yt_length":"3883"},{"streamer":"destiny","yt_length":"3715"},{"streamer":"zekent","yt_length":"3428"},{"streamer":"athenelive","yt_length":"1673"},{"streamer":"frommaplestreet","yt_length":"1614"},{"streamer":"keyorikeys","yt_length":"1410"},{"streamer":"riotgamesturkish","yt_length":"1397"},{"streamer":"vman7","yt_length":"1022"},{"streamer":"tiensinoakuma","yt_length":"967"},{"streamer":"affenklappe","yt_length":"748"},{"streamer":"teamkeyd","yt_length":"747"},{"streamer":"lagtvmaximusblack","yt_length":"683"},{"streamer":"lolgameru","yt_length":"665"},{"streamer":"gruntartv","yt_length":"585"},{"streamer":"entenzwerg","yt_length":"579"},{"streamer":"lolgameru_cauthonpro","yt_length":"506"},{"streamer":"basickz","yt_length":"488"},{"streamer":"ilysuiteheart","yt_length":"491"},{"streamer":"kireiautumn","yt_length":"485"},{"streamer":"ultimavv","yt_length":"471"}]}
Java class:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
String response = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
And my activity:
public class AndroidJSONParsingActivity extends ListActivity {
// url to make request
private static String url = "http://ololo.tv/vasa";
// JSON Node names
private static final String TAG_DATA = "data";
private static final String TAG_STREAMER = "streamer";
private static final String TAG_VIEWERS = "yt_length";
// contacts JSONArray
JSONArray data = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser Parser = new JSONParser();
// getting JSON string from URL
JSONObject json = null;
json = Parser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
data = json.getJSONArray(TAG_DATA);
// looping through All Contacts
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
// Storing each json item in variable
String streamer = c.getString(TAG_STREAMER);
String viewers = c.getString(TAG_VIEWERS);
//String link = c.getString();
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_STREAMER, streamer);
map.put(TAG_VIEWERS, viewers);
//map.put(TAG_URL, link);
// adding HashList to ArrayList
dataList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, dataList,
R.layout.list_item,
new String[] { TAG_STREAMER, TAG_VIEWERS /*TAG_URL*/ }, new int[] {
R.id.streamer, R.id.viewers /*R.id.url*/ });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.streamer)).getText().toString();
String viewers_count = ((TextView) view.findViewById(R.id.viewers)).getText().toString();
//String url = ((TextView) view.findViewById(R.id.url)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_STREAMER, name);
in.putExtra(TAG_VIEWERS, viewers_count);
//in.putExtra(TAG_PHONE_MOBILE, url);
startActivity(in);
}
});
}
}
I tried using breakpoints, and see that when I put a breakpoint after GetEntity, the program doesn't get there because it crashed early, or something.
This my async task.
public class ParsingTask extends AsyncTask<String, Void, Void>{
JSONParser Parser = new JSONParser();
protected Void doInBackground(String... urls) {
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
JSONObject json = Parser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
data = json.getJSONArray(TAG_DATA);
// looping through All Contacts
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
// Storing each json item in variable
String streamer = c.getString(TAG_STREAMER);
String viewers = c.getString(TAG_VIEWERS);
//String link = c.getString();
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_STREAMER, streamer);
map.put(TAG_VIEWERS, viewers);
//map.put(TAG_URL, link);
// adding HashList to ArrayList
dataList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, dataList,
R.layout.list_item,
new String[] { TAG_STREAMER, TAG_VIEWERS /*TAG_URL*/ }, new int[] {
R.id.streamer, R.id.viewers /*R.id.url*/ });
setListAdapter(adapter);
return null;
}
protected void onProgressUpdate() {
}
protected void onPostExecute() {
}
}
ListAdapter error, seems like something wrong in "this". This my version how cut off code, where it stop return variables. Sorry for bad english, but i hope you understand me :)
Add my php json maker. Mb problem there?!
<?php
mysql_connect("localhost","root","");
if (!mysql_select_db("ololo")) {
echo "Unable to select ololo: " . mysql_error();
}
$sql=mysql_query("select streamer, yt_length from pm_videos where category='1'");
if(!$sql) exit("Error - ".mysql_error().", ".$tmp_q);
while($row=mysql_fetch_assoc($sql)){
$output[]=$row;
}
$json = json_encode($output);
header('Content-Type: application/json');
print "{\"data\": ${json}}";
mysql_close();
?>
You programm crashes because you are running
json = Parser.getJSONFromUrl(url);
in the UI Thread context. You have to use an AsyncTask
Code looks good. The only problem is that
public class ParsingTask extends AsyncTask<String, Void, ArrayList<HashMap<String, String>>>{
JSONParser Parser = new JSONParser();
protected Void doInBackground(String... urls) {
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
JSONObject json = Parser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
data = json.getJSONArray(TAG_DATA);
// looping through All Contacts
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
// Storing each json item in variable
String streamer = c.getString(TAG_STREAMER);
String viewers = c.getString(TAG_VIEWERS);
//String link = c.getString();
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_STREAMER, streamer);
map.put(TAG_VIEWERS, viewers);
//map.put(TAG_URL, link);
// adding HashList to ArrayList
dataList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
return dataList;
}
protected void onPostExecute(ArrayList<HashMap<String, String>> dataList) {
ListAdapter adapter = new SimpleAdapter(AndroidJSONParsingActivity.this, dataList,
R.layout.list_item,
new String[] { TAG_STREAMER, TAG_VIEWERS /*TAG_URL*/ }, new int[] {
R.id.streamer, R.id.viewers /*R.id.url*/ });
setListAdapter(adapter);
}
Have you heard about gson (docs)?
public static final class Content {
#SerializedName("streamer") // you don't need to specify this, JFYI
String streamer;
#SerializedName("yt_length") // you don't need to specify this, JFYI
String yt_length;
}
public static final class Data {
#SerializedName("data")
List<Content> data;
}
public static void main (String[] args) {
Gson gson = new GsonBuilder().create();
Data data = gson.fromJson(jsonString, Data.class);
}
And remember, you cannot call network operations on UI thread! this is reason of what you have for now.
json data
[
-{
Cat_Id: 21
Cat_Title: "Electronics"
Cat_Description: null
Cat_Status: 0
Cat_CreatedBy: 0
Cat_CreatedDate: "0001-01-01T00:00:00"
Cat_UpdatedBy: 0
Cat_UpdatedDate: "0001-01-01T00:00:00"
}
Category class
public class Category {
public int Cat_Id;
public String Cat_Title = null;;
public Category() {
}
public int getCat_Id() {
return Cat_Id;
}
public void setCat_Id(int Cat_Id) {
this.Cat_Id = Cat_Id;
}
}
BaseActivity
public class BaseActivity extends Activity {
public ProgressDialog progressDialog;
public SharedPreferences prefs;
public JSONObject jsonObject;
public JSONObject jsonObject1;
public static String pref_setting = "Category_setting";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO Auto-generated method stub
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading..");
prefs = PreferenceManager.getDefaultSharedPreferences(this);
Preferences.AppContext = this;
}
protected void onStop() {
super.onStop();
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
Soap
public class Soap {
// public static String BaseURL = "";
public static String BaseURL = "";
public static String imgURL = "";
public static String getSoapResponseByGet(String postFixOfUrl)
throws ClientProtocolException, IOException {
if (Preferences.AppContext != null
&& Preferences.isOnline(Preferences.AppContext)) {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(BaseURL + postFixOfUrl);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
String xmlString = EntityUtils.toString(entity);
return xmlString.toString();
} else {
return "{\"error\":{\"no_internet\":\"No internet connection\"}}";
}
}
public static String getSoapResponse(String postFixOfUrl)
throws ClientProtocolException, IOException {
if (Preferences.AppContext != null
&& Preferences.isOnline(Preferences.AppContext)) {
HttpPost httpPost = new HttpPost(BaseURL + postFixOfUrl);
StringEntity se = new StringEntity("", HTTP.UTF_8);
se.setContentType("text/xml");
httpPost.setHeader("Content-Type", "text/xml;charset=utf-8");
httpPost.setEntity(se);
HttpClient httpClient = new DefaultHttpClient();
BasicHttpResponse httpResponse = (BasicHttpResponse) httpClient
.execute(httpPost);
HttpEntity r_Entity = httpResponse.getEntity();
String xmlString = EntityUtils.toString(r_Entity);
return xmlString.toString();
} else {
return "{\"error\":{\"no_internet\":\"No internet connection\"}}";
}
}
public static String getSoapResponseByPost(String postFixOfUrl,
ArrayList<NameValuePair> nameValuePairs)
throws ClientProtocolException, IOException {
if (Preferences.AppContext != null
&& Preferences.isOnline(Preferences.AppContext)) {
HttpPost httpPost = new HttpPost(BaseURL + postFixOfUrl);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpClient httpClient = new DefaultHttpClient();
BasicHttpResponse httpResponse = (BasicHttpResponse) httpClient
.execute(httpPost);
HttpEntity r_Entity = httpResponse.getEntity();
String xmlString = EntityUtils.toString(r_Entity);
return xmlString.toString();
} else {
return "{\"error\":{\"no_internet\":\"No internet connection\"}}";
}
}
// ////////// api for Category //////////////
http://sharafdg.digitarabia.com/sharafdg/api/Category
public static String apiGetCategory() throws ClientProtocolException,
IOException {
String result = Soap.getSoapResponseByGet("api/Category");
Log.e("SOAP", result);
return result;
}
public static String apiGetstore(int catid, int brandid, int modelid,
String variant) throws ClientProtocolException, IOException {
String result = Soap.getSoapResponseByGet("api/stores/?catid=" + catid
+ "&brandid=" + brandid + "&modelid=" + modelid + "&variant="
+ variant);
Log.e("SOAPSTORE", "api/stores/?catid=" + catid);
Log.e("SOAPSTORE", "api/stores/?&brandid=" + brandid);
Log.e("SOAPSTORE", "api/stores/?&modelid=" + modelid);
Log.e("SOAPSTORE", "api/stores/?&variant=" + variant);
return result;
}
-------------- post method hoy to -----------------
http://kallapp.madword-media.co.uk/company.php?category_id=11
http://kallapp.madword-media.co.uk/categories.php
public static String apiGetCategory() throws ClientProtocolException,
IOException {
ArrayList<NameValuePair> alNameValuePairs = new
ArrayList<NameValuePair>();
String result = Soap.getSoapResponseByPost("categories.php",
alNameValuePairs);
return result;
}
public static String apiGetcompanies(String category_id)
throws ClientProtocolException, IOException {
ArrayList<NameValuePair> alNameValuePairs = new
ArrayList<NameValuePair>();
// NameValuePair nameValuePairs = new BasicNameValuePair("",
// category_id);
// alNameValuePairs.add(nameValuePairs);
String result = Soap.getSoapResponse("company.php?category_id="
+ category_id);
Log.e("SOAP", result);
return result;
}
public static String apiGetDepaName(String category_id, String
company_id)
throws ClientProtocolException, IOException {
ArrayList<NameValuePair> alNameValuePairs = new
ArrayList<NameValuePair>();
NameValuePair nameValuePair = new BasicNameValuePair("category_id",
category_id);
alNameValuePairs.add(nameValuePair);
nameValuePair = new BasicNameValuePair("company_id", company_id);
alNameValuePairs.add(nameValuePair);
String result =
Soap.getSoapResponseByPost("department.php?",alNameValuePairs);
return result;
}
Category_list
public class Category_list extends BaseActivity {
int currentCategoryid;
private ArrayList<Category> cat = new ArrayList<Category>();
ArrayList<String> list = new ArrayList<String>();
Spinner spinner;
Button btncompare;
private int catid;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO Auto-generated method stub
setContentView(R.layout.activity_webservices);
spinner = (Spinner) findViewById(R.id.spinner);
btncompare = (Button) findViewById(R.id.btncompare);
spinner.setOnItemSelectedListener(new OnItemSelected());
new getCategoryTask().execute();
btncompare.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getBaseContext(), Store.class);
intent.putExtra("catid", catid);
startActivity(intent);
}
});
}
public class OnItemSelected implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// ((TextView) arg0.getChildAt(0)).setTextColor(Color.GREEN);
catid = cat.get(arg2).Cat_Id;
String cateid = String.valueOf(catid);
Log.e("cateid_category", cateid);
// new getBrandTask().execute();
}
public void onNothingSelected(AdapterView<?> arg0) {
}
}
private class getCategoryTask extends AsyncTask<Void, Void, Void> {
Category category;
String categoryJsonStr;
public getCategoryTask() {
category = new Category();
}
protected void onPreExecute() {
super.onPreExecute();
// progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
-----------------------admin email-pass-------------
JSONObject jsonObject = new JSONObject(userJsonStr);//
jsonUserArray.getJSONObject(i);
currentUserid = jsonObject.getInt("Use_Id");
if (currentUserid > 0) {
if (!jsonObject.isNull("Use_Id")) {
id = jsonObject.getInt("Use_Id");
}
}
--------------------kallapp---------
try {
Log.i("categoryJsonStr", categoryJsonStr);
JSONObject jsonObject = new JSONObject(categoryJsonStr);
JSONArray jsonCatArray = jsonObject.getJSONArray("categories");
for (int i = 0; i < jsonCatArray.length(); i++) {
Category objcategory = new Category();
jsonObject = jsonCatArray.getJSONObject(i);
--------------------------------------------------------------
try {
// categoryJsonStr = Soap.apiGetCategory();
Log.e("categoryJsonStr", categoryJsonStr);
JSONArray jsonCatArray = new JSONArray(categoryJsonStr);
Category category = new Category();
// category.Cat_Id = -1;
category.Cat_Title = "Select Category";
cat.add(category);
list.add(category.Cat_Title);
for (int i = 0; i < jsonCatArray.length(); i++) {
Category objcategory = new Category();
JSONObject jsonObject = jsonCatArray.getJSONObject(i);
currentCategoryid = jsonObject.getInt("Cat_Id");
if (!jsonObject.isNull("Cat_Title")) {
objcategory.setCat_Title(jsonObject
.getString("Cat_Title"));
}
if (!jsonObject.isNull("Cat_Id")) {
objcategory.setCat_Id(jsonObject.getInt("Cat_Id"));
}
cat.add(objcategory);
list.add(objcategory.Cat_Title);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
public void onPostExecute(Void result) {
super.onPostExecute(result);
// progressDialog.dismiss();
spinner.setAdapter(new ArrayAdapter<String>(Category_list.this,
android.R.layout.simple_spinner_item, list));
spinner.setSelection(0, true);
}
}
}
-------------more than one item fill--------
store_lists.add(objStore_list);
public void onPostExecute(Void result) {
super.onPostExecute(result);
store_adapter = new Store_adapter(Store.this, store_lists);
lv_store.setAdapter(store_adapter);
store_adapter.notifyDataSetChanged();
}
Preferences
public class Preferences {
public static Context AppContext = null;
public static String categoryid;
public static boolean isOnline(Context c) {
ConnectivityManager cm = (ConnectivityManager) c
.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isConnectedOrConnecting();
}
}
Store_adapter
private Context mContext;
private int ImageCount;
private ArrayList<Store_list> store_lists = new ArrayList<Store_list>();
public ImageLoader imageLoader;
ImageView imgsave, imgpackage, img_up_arrow, img_dun_arrow;
TextView txtsave;
RelativeLayout relatv;
public Store_adapter(Context c, ArrayList<Store_list> store_lists) {
mContext = c;
this.store_lists = store_lists;
this.ImageCount = store_lists.size();
imageLoader = new ImageLoader(c);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
// ImageCount = store_lists.size();
return this.ImageCount;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
this.ImageCount = store_lists.size();
}
public void remove(int position) {
store_lists.remove(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View vi = inflater.inflate(R.layout.storelist, parent, false);
TextView name = (TextView) vi.findViewById(R.id.txtprise);
ImageView imgview = (ImageView) vi.findViewById(R.id.imgve);
Store_list list = store_lists.get(position);
imageLoader.DisplayImage(list.Store_logo, imgview);
name.setText(String.valueOf(list.Mod_Price));
return vi;
}
}
menifestfile
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"
/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
/>
public static String getSoapResponse(String postFixOfUrl) {
try {
if (General.AppContext != null
&& General.isOnline(General.AppContext)) {
HttpGet httpget = new HttpGet(BaseURL + postFixOfUrl);
Log.i("SOAP", "URI:" + BaseURL + postFixOfUrl);
httpget.setHeader("Content-Type",
"application/json;charset=utf-8");
HttpClient httpclient = new DefaultHttpClient();
BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient
.execute(httpget);
HttpEntity r_entity = httpResponse.getEntity();
String xmlString = EntityUtils.toString(r_entity);
return xmlString.toString();
} else {
// return
// "[{\"erorr\":{\"no_internet\":\"No internet connection\"}}]";
if (General.AppActivity != null) {
General.AppActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(
General.AppContext,
General.AppContext
.getResources()
.getString(
R.string.no_internet_connection),
Toast.LENGTH_SHORT).show();
}
});
}
return null;
}
} catch (Exception e) {
HandleException.catchException(e, true);
}
return null;
}
// post method
public static String getSoapResponseByPost(String postFixOfUrl,
ArrayList<NameValuePair> nameValuePairs)
throws ClientProtocolException, IOException {
try {
if (General.AppContext != null
&& General.isOnline(General.AppContext)) {
HttpPost httppost = new HttpPost(BaseURL + postFixOfUrl);
Log.i("SOAP", "URI:" + BaseURL + postFixOfUrl);
// httppost.setHeader("Content-Type",
// "text/html;charset=utf-8");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,
"UTF-8"));
HttpClient httpclient = new DefaultHttpClient();
BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient
.execute(httppost);
HttpEntity r_entity = httpResponse.getEntity();
String xmlString = EntityUtils.toString(r_entity);
return xmlString.toString();
} else {
// return
// "[{\"erorr\":{\"no_internet\":\"No internet connection\"}}]";
if (General.AppActivity != null) {
General.AppActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(
General.AppContext,
General.AppContext
.getResources()
.getString(
R.string.no_internet_connection),
Toast.LENGTH_SHORT).show();
}
});
}
return null;
}
} catch (Exception e) {
HandleException.catchException(e, true);
}
return null;
}
public static String getSoapResponseForImage(String postFixOfUrl,
List<NameValuePair> nameValuePairs,
List<NameValuePair> filenameValuePairs) {
String xmlString = null;
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(BaseURL + postFixOfUrl);
try {
MultipartEntity entity = new MultipartEntity();
for (int index = 0; index < filenameValuePairs.size(); index++) {
File myFile = new File(filenameValuePairs.get(index).getValue());
if (myFile.exists()) {
FileBody fileBody = new FileBody(myFile);
entity.addPart(filenameValuePairs.get(index).getName(),
fileBody);
}
}
for (int index = 0; index < nameValuePairs.size(); index++) {
entity.addPart(nameValuePairs.get(index).getName(),
new StringBody(nameValuePairs.get(index).getValue(),
Charset.forName("UTF-8")));
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity r_entity = response.getEntity();
xmlString = EntityUtils.toString(r_entity);
} catch (IOException e) {
e.printStackTrace();
}
Log.d("SOAP ", "Result : " + xmlString.toString());
return xmlString.toString();
}
public class ParsedResponse {
public Object o;
public boolean error = false;
}
public class General {
public static Context AppContext = null;
public static Activity AppActivity = null;
public static boolean isOnline(Context c) {
ConnectivityManager cm = (ConnectivityManager) c
.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isConnectedOrConnecting();
}}
public class BaseActivity extends Activity {
protected SharedPreferences prefs;
public ProgressDialog progressDialog;
General.AppContext = getApplicationContext();
General.AppActivity = BaseActivity.this;
prefs = PreferenceManager.getDefaultSharedPreferences(this);}
public class ErrorMgmt {
private Boolean error;
private String errorMessage;
private String exceptionMessage;
public ErrorMgmt(String exceptionMessage) {
error = false;
errorMessage = "";
this.exceptionMessage = exceptionMessage;
}
public ErrorMgmt() {
error = false;
errorMessage = "";
exceptionMessage = "";
}
public String getErrorMessage() {
if (error) {
if (errorMessage.equals("")) {
return exceptionMessage;
} else {
return errorMessage;
}
}
return null;
}
#SuppressWarnings("rawtypes")
public Boolean strError(String JsonResponse) {
this.error = false;
errorMessage = "";
try {
JSONObject objJson = new JSONObject(JsonResponse);
String strJson = objJson.getString("JsonResponse");
if(!strJson.equals("Please enter valid email")) {
this.error = true ;
errorMessage = "";
} else {
this.error = false;
}
} catch (JSONException e) {
this.error = true;
errorMessage = "";
HandleException.catchException(e, true);
}
return this.error;
}
#SuppressWarnings("rawtypes")
public Boolean isObjError(String JsonResponse) {
this.error = false;
errorMessage = "";
try {
JSONObject objJson = new JSONObject(JsonResponse);
if (objJson != null && !objJson.isNull("error") ) {
this.error = true;
Iterator IError = objJson.keys();
errorMessage = "";
while (IError.hasNext()) {
String key = (String) IError.next();
errorMessage += objJson.getString(key) + "\n";
}
} else if (objJson != null && !objJson.isNull("statusCode")) {
Integer statusCode = objJson.getInt("statusCode");
if (statusCode > 200) {
this.error = true;
} else {
this.error = false;
}
} else {
this.error = false;
}
} catch (JSONException e) {
this.error = true;
errorMessage = "";
HandleException.catchException(e, true);
}
return this.error;
}
#SuppressWarnings("rawtypes")
public Boolean isError(String JsonResponse) {
this.error = false;
errorMessage = "";
try {
JSONArray arrJson = new JSONArray(JsonResponse);
if (!arrJson.isNull(0) && !arrJson.getJSONObject(0).isNull("erorr")) {
this.error = true;
JSONObject objError = arrJson.getJSONObject(0);
Iterator IError = objError.keys();
errorMessage = "";
while (IError.hasNext()) {
String key = (String) IError.next();
errorMessage += objError.getString(key) + "\n";
}
} else if (!arrJson.isNull(0)
&& !arrJson.getJSONObject(0).isNull("statusCode")) {
Integer statusCode = arrJson.getJSONObject(0).getInt(
"statusCode");
if (statusCode > 200) {
this.error = true;
} else {
this.error = false;
}
} else {
this.error = false;
}
} catch (JSONException e) {
this.error = true;
errorMessage = "";
HandleException.catchException(e, true);
}
return this.error;
}
public void SetForsedError(Boolean val) {
error = true;
}
}
// Api for register with Email
public static ParsedResponse apiRegister(String name, String email,
String password) throws Exception {
ArrayList<NameValuePair> alNameValuePairs = new ArrayList<NameValuePair>();
NameValuePair nameValuePair = new BasicNameValuePair("name", name);
alNameValuePairs.add(nameValuePair);
nameValuePair = new BasicNameValuePair("email", email);
alNameValuePairs.add(nameValuePair);
nameValuePair = new BasicNameValuePair("password", password);
alNameValuePairs.add(nameValuePair);
// nameValuePair = new BasicNameValuePair("fb_uid", "");
// alNameValuePairs.add(nameValuePair);
String result = Soap.getSoapResponseByPost("user/register",
alNameValuePairs);
Log.e("apiRegister", result);
ErrorMgmt errMgmt = new ErrorMgmt(General.AppContext.getResources()
.getString(R.string.error_loading_data));
ParsedResponse p = new ParsedResponse();
p.error = false;
if (result != null && !result.equals("")) {
JSONObject jObject = new JSONObject(result);
String code = "";
if (!jObject.isNull("statusCode")) {
code = jObject.getString("statusCode");
}
if (code.equals("200")) {
JSONArray jsonArray = jObject.getJSONArray("User");
if (jsonArray.length() > 0) {
ArrayList<UserData> arrayList = new ArrayList<UserData>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
UserData objUserData = new UserData();
if (!jsonObject.isNull("uid")) {
objUserData.uid = jsonObject.getString("uid");
}
if (!jsonObject.isNull("name")) {
objUserData.name = jsonObject.getString("name");
}
if (!jsonObject.isNull("email")) {
objUserData.email = jsonObject.getString("email");
}
if (!jsonObject.isNull("password")) {
objUserData.password = jsonObject
.getString("password");
}
if (!jsonObject.isNull("created_date")) {
objUserData.created_date = jsonObject
.getString("created_date");
}
if (!jsonObject.isNull("status")) {
objUserData.status = jsonObject.getString("status");
}
if (!jsonObject.isNull("fb_uid")) {
objUserData.fb_uid = jsonObject.getString("fb_uid");
}
if (!jsonObject.isNull("account_type")) {
objUserData.account_type = jsonObject
.getString("account_type");
}
if (!jsonObject.isNull("profile_img")) {
objUserData.profile_img = jsonObject
.getString("profile_img");
}
if (!jsonObject.isNull("birthdate")) {
objUserData.birthdate = jsonObject
.getString("birthdate");
}
if (!jsonObject.isNull("city")) {
objUserData.city = jsonObject.getString("city");
}
JSONArray jsonArray2 = jsonObject
.getJSONArray("usersubscribe");
if (jsonArray2.length() > 0) {
for (int i1 = 0; i1 < jsonArray2.length(); i1++) {
JSONObject jsonObject2 = jsonArray2
.getJSONObject(i1);
if (!jsonObject2.isNull("isSubscribe")) {
objUserData.isSubscribe = jsonObject2
.getString("isSubscribe");
}
if (!jsonObject2.isNull("amount")) {
objUserData.amount = jsonObject2
.getString("amount");
}
}
}
arrayList.add(objUserData);
p.o = arrayList;
}
} else {
errMgmt = new ErrorMgmt(General.AppActivity.getResources()
.getString(R.string.err_norecords));
errMgmt.SetForsedError(true);
p.o = errMgmt;
p.error = true;
}
}
if (code.equals("401")) {
errMgmt = new ErrorMgmt(General.AppActivity.getResources()
.getString(R.string.allready_regi));
errMgmt.SetForsedError(true);
p.o = errMgmt;
p.error = true;
}
} else {
errMgmt = new ErrorMgmt(General.AppActivity.getResources()
.getString(R.string.err_norecords));
errMgmt.SetForsedError(true);
p.o = errMgmt;
p.error = true;
}
return p;
}
// Login with Facebook
private class GetFacebookLogin extends AsyncTask<Void, Void, Void> {
private ParsedResponse p = null;
private String message = "";
private Boolean error = false;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
p = new ParsedResponse();
p = Soap.apiUserLoginFacebook(fbID);
if (p.error) {
ErrorMgmt errmgmt = (ErrorMgmt) p.o;
message = errmgmt.getErrorMessage();
error = true;
} else {
arrayList.clear();
arrayList.addAll((ArrayList<UserData>) p.o);
error = false;
}
} catch (Exception e) {
message = "problem in loading data";
error = true;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
progressDialog.dismiss();
if (error) {
new AlertDialog.Builder(Register_Login_Screen.this)
.setMessage(message)
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
}).show();
} else {
UserData objUserData = new UserData();
for (int i = 0; i < arrayList.size(); i++) {
objUserData = arrayList.get(i);
}
String profileImage = "";
try {
URL image_value = new URL("http://graph.facebook.com/"
+ fbID + "/picture?height=150&width=150");
profileImage = String.valueOf(image_value);
Log.e("fb_image_path", "" + image_value);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Editor e = prefs.edit();
e.putBoolean(General.PREFS_login, true);
e.putString(General.PREFS_Uid, objUserData.uid);
e.putString(General.PREFS_name, objUserData.name);
e.putString(General.PREFS_email, objUserData.email);
e.putString(General.PREFS_fb_uid, objUserData.fb_uid);
e.putString(General.PREFS_logintype, General.PREFS_valuefblogin);
if (objUserData.profile_img != null
&& !objUserData.profile_img.equals("")) {
e.putString(General.PREFS_profile_img,
objUserData.profile_img);
} else {
e.putString(General.PREFS_profile_img, profileImage);
}
e.putString(General.PREFS_account_type,
objUserData.account_type);
e.putString(General.PREFS_birthdate, objUserData.birthdate);
e.putString(General.PREFS_city, objUserData.city);
e.putString(General.PREFS_subscribed, objUserData.isSubscribe);
e.putString(General.PREFS_amount, objUserData.amount);
String[] strings = null;
for (int i = 0; i < objUserData.screenerArr.size(); i++) {
String queString = objUserData.screenerArr.get(i);
strings = queString.split(",");
String question1 = strings[0];
e.putString("RosaRosa_screener_question" + (i + 1),
question1);
e.putBoolean("RosaRosa_screener_ans" + (i + 1), true);
String ans1 = strings[1];
e.putString(
"RosaRosa_screener_question" + (i + 1) + "_ans",
ans1);
Log.e("question", "" + question1 + ans1);
}
e.commit();
Toast.makeText(Register_Login_Screen.this, R.string.succ_login,
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Register_Login_Screen.this,
Personal_Stylist_Activity.class);
startActivity(intent);
finish();
}
}
}

SharedPreferences not reading Data

I'm saving two parts of data the users password and username to use at a later data and a random combination of letters to then check when the app is executed again to avoid the login screen again.
I had this working yesterday and for some reason, I expect I misplaced code when adding a feature and now cannot get it working again, I've tried all day to fix it and yet I cannot.
EDIT1: For some reason, it goes to the else statement on the "CheckPrefs" method, which I CANNOT UNDERSTAND.
EDIT2: It saves the preferences fine and goes to the intent but, it just can't read it.
Code:
public static final String PREFS_NAME = "MyPregs";
public static final String PREFS_CHECK = "CheckSignedIn";
public static final String UID ="";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
CheckPrefs();
// Login button clicked
ok = (Button) findViewById(R.id.btn_login);
ok.setOnClickListener(this);
result = (TextView) findViewById(R.id.lbl_result);
}
private void CheckPrefs() {
// TODO Auto-generated method stub
//checks to see if the user has signed in before if they have it gets there data from SharedPreferences and checks against our database via HttpPost.
SharedPreferences settings = getSharedPreferences(PREFS_CHECK, 0);
String SCheck1 = settings.getString("key4", null);
if (SCheck1 != null && equals(UID)) {
Intent c = new Intent(this, CheckUserInfo.class);
startActivity(c);
} else {
}
}
//create bracket.
public void postLoginData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
/* login.php returns true if username and password is equal to saranga */
HttpPost httppost = new HttpPost("http://gta5news.com/login.php");
try {
// Add user name and password
uname = (EditText) findViewById(R.id.txt_username);
String username = uname.getText().toString();
pword = (EditText) findViewById(R.id.txt_password);
String password = pword.getText().toString();
SharedPreferences signedin = getSharedPreferences(PREFS_CHECK, 0);
SharedPreferences.Editor editor1 = signedin.edit();
editor1.putString("key4", UID);
editor1.commit();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("key1", username);
editor.putString("key2", password);
editor.commit();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
Log.w("HttpPost", "Execute HTTP Post Request");
HttpResponse response = httpclient.execute(httppost);
String str = inputStreamToString(response.getEntity().getContent())
.toString();
Log.w("HttpPost", str);
if (str.toString().equalsIgnoreCase("true")) {
Log.w("HttpPost", "TRUE");
result.setText("Login successful");
try {Thread.sleep(250);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent login = new Intent(LogIn.this, ChatService.class);
startActivity(login);
} else {
Log.w("HttpPost", "FALSE");
result.setText(str);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
public void onClick(View view) {
if (view == ok) {
postLoginData();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(pword.getWindowToken(), 0);
}
// Click end
}
// if statement
}
// class ends here
need to see where you are saving your preferences, so we can match it up with how you're calling your preferences... but, is this a typo?
public static final String PREFS_NAME = "MyPregs";
Should it be "MyPrefs" instead of "MyPregs"?
You have
if (SCheck1 != null && equals(UID))
but do you maybe mean to say
if (SCheck1 != null && !SCheck.equals(UID))
?
You could use the 'reverse comparison' pattern too:
if (UID.equals(SCheck1)) {
} else {
}
This way, you don't have to bother checking SCheck1 == null. UID.equals(null) will return false instead of null.equals(UID) throwing a NullPointerException.

android java run activity without restarting it

I created simple application which would login to DB and get data from it. But now I found a problem: If you in the first time write wrong login data and try to login second time it won't work. You have to restart it.
I think there is a problem in this code: EDITED
public class MyMoodleApplicationActivity extends Activity {
/** Called when the activity is first created. */
EditText username;
EditText password;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
username = (EditText)findViewById(R.id.username);
password = (EditText)findViewById(R.id.password);
final Button loginButton = (Button)findViewById(R.id.login);
loginButton.setOnClickListener(loginListener);
final Button clearButton = (Button)findViewById(R.id.clear);
clearButton.setOnClickListener(clearListener);
}
private OnClickListener loginListener = new OnClickListener(){
public void onClick(View v){
String usr = username.getText().toString();
String psw = password.getText().toString();
System.out.println("Username: "+usr);
System.out.println("Password: "+psw);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("usern",""+usr));
nameValuePairs.add(new BasicNameValuePair("passw",""+psw));
InputStream is = null;
String result = "";
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://ik.su.lt/*****");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
String usernameFromDB = "";
String firstnameFromDB = "";
String lastnameFromDB = "";
String emailFromDB = "";
String phoneFromDB = "";
String skypeFromDB = "";
String cityFromDB = "";
String descriptionFromDB = "";
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
usernameFromDB = json_data.getString("username");
firstnameFromDB = json_data.getString("firstname");
lastnameFromDB = json_data.getString("lastname");
emailFromDB = json_data.getString("email");
phoneFromDB = json_data.getString("phone1");
skypeFromDB = json_data.getString("skype");
cityFromDB = json_data.getString("city");
descriptionFromDB = json_data.getString("description");
System.out.println(usernameFromDB+ " " + firstnameFromDB+" "+lastnameFromDB+" "
+ emailFromDB + " " + phoneFromDB +" " + skypeFromDB+ " " + cityFromDB + " "+
descriptionFromDB);
}
}
catch(JSONException e){
AlertDialog alertDialog = new AlertDialog.Builder(MyMoodleApplicationActivity.this).create();
alertDialog.setTitle("Klaida!");
alertDialog.setMessage("Toks vartotojas neegzistuoja");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
return;
}
});
alertDialog.show();
Log.e("log_tag", "Error parsing data "+e.toString());
}
if(usr.length()== 0){
AlertDialog alertDialog = new AlertDialog.Builder(MyMoodleApplicationActivity.this).create();
alertDialog.setTitle("Klaida!");
alertDialog.setMessage("Jūs neįvedėte slapyvardžio");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
return;
}
});
alertDialog.show();
}
else if(psw.length()==0){
AlertDialog alertDialog = new AlertDialog.Builder(MyMoodleApplicationActivity.this).create();
alertDialog.setTitle("Klaida!");
alertDialog.setMessage("Jūs neįvedėte slaptažodžio");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
return;
}
});
alertDialog.show();
}
else if (usr.equals(usernameFromDB)){
Intent in = new Intent(getApplicationContext(), LoggedUser.class);
in.putExtra("firstname", firstnameFromDB);
in.putExtra("lastname", lastnameFromDB);
in.putExtra("email", emailFromDB);
in.putExtra("phone1", phoneFromDB);
in.putExtra("skype", skypeFromDB);
in.putExtra("city", cityFromDB);
in.putExtra("description", descriptionFromDB);
startActivity(in);
finish();
}
}};
private OnClickListener clearListener = new OnClickListener(){
#Override
public void onClick(View v){
username.setText("");
password.setText("");
}
};
In these if statements I check if username and password you enter is empty username is not equal to the one in database.
How to rewrite the code that it would work?
Edited:
I have user john in DB but if I write John in login field and press login button it won't say that there is not the John user. And in LogCat I see that json stream is readed. Is there a way to set up a rule that upercase and lowercase letters would be different?

Categories

Resources