I'm trying to do a PIN input as a dialog.
This part is working fine. But when I enter my pin and try to compare it to my requested pin it just closes my dialog.
So here is my code:
PinInput.java
package com.ts.techassi.ts;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class PinInput extends DialogFragment {
public final static String EXTRA_MESSAGE = "tuerschild.saschalautenschlaege.tuerschild.MESSAGE";
Context context;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.pin_input, null));
Log.i("LOL", "Started");
builder.setMessage("Enter PIN")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Uri url = readUrl();
Dialog f = (Dialog) dialog;
// String ts_id = url.getLastPathSegment();
EditText pin = (EditText)f.findViewById(R.id.pin);
TextView test = (TextView) f.findViewById(R.id.response);
String pinString = pin.getText().toString();
try {
String response = new Http().execute().get();
// Log.i("test", response);
if( response == pinString) {
Boolean isLauncher = isMyAppLauncherDefault();
if(isLauncher == true){
resetPreferredLauncherAndOpenChooser(context);
}
} else {
PinInput.this.getDialog().cancel();
}
} catch (Exception e) {
e.printStackTrace();
Log.i("Test",e.toString());
}
}
})
.setNegativeButton("Abbrechen", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
return builder.create();
}
public Uri readUrl() {
String fileDirectory = Environment.getExternalStorageDirectory()+"/dbDoorsign/url.txt";
File file = new File(fileDirectory);
StringBuilder text = new StringBuilder();
;
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
}
br.close();
}
catch (IOException e) {
}
return Uri.parse(text.toString());
}
private boolean isMyAppLauncherDefault() {
final IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
filter.addCategory(Intent.CATEGORY_HOME);
List<IntentFilter> filters = new ArrayList<IntentFilter>();
filters.add(filter);
final String myPackageName = getActivity().getPackageName();
List<ComponentName> activities = new ArrayList<ComponentName>();
final PackageManager packageManager = (PackageManager) getActivity().getPackageManager();
packageManager.getPreferredActivities(filters, activities, null);
for (ComponentName activity : activities) {
if (myPackageName.equals(activity.getPackageName())) {
return true;
}
}
return false;
}
public static void resetPreferredLauncherAndOpenChooser(Context context) {
PackageManager packageManager = context.getPackageManager();
ComponentName componentName = new ComponentName(context, FakeLauncherActivity.class);
packageManager.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
Intent selector = new Intent(Intent.ACTION_MAIN);
selector.addCategory(Intent.CATEGORY_HOME);
selector.putExtra(EXTRA_MESSAGE, "1");
selector.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(selector);
packageManager.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, PackageManager.DONT_KILL_APP);
}
}
My second file Http.java
package com.ts.techassi.ts;
import android.os.AsyncTask;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Http extends AsyncTask<String, Void, String> {
String USER_AGENT = "Mozilla/5.0";
private TextView scanResults;
#Override
protected String doInBackground(String... url) {
try {
return sendGet();
} catch (Exception e) {
e.printStackTrace();
return e.toString();
}
}
private String sendGet() throws Exception {
String url = "http://my.url.com";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
// System.out.println(response.toString());
return response.toString();
}
}
EDIT 1:
Changed if( pinString == response) to if( pinString.equals(response))
So I thinks thats all you need. I hope you can help me.
The problem is this line:
if( response == pinString) {
Never compare Strings like this in Java. Change it to:
if( pinString.equals(response) ) {
The reason is that, in Java, == operator compares instances, not contents. It works for primitives (like ints and longs), but Objects, including Strings, need to be compared with the .equals() method, which compares the contents, not the instance.
Related
I have many QR codes ex. Example on imgur, which has peoples' names, numbers, and emails, and I need to scan them. The data comes in something like this: "joe,1234567890,joe#joe.com". I want to write an app that uploads the data to a google sheet and I found a tutorial online from crazycodersclub.com, but when I do the same thing it gives me an error, something like:
Exception: Invalid argument: URL (line 11, file "Code")
Google Script Code
function doGet(e){
var url = encodeUrl("https://docs.google.com/spreadsheets/d/1IEAHcv2n33YO9d7IbfWNVLv2Hl1Q1UXveazPcgMZrMs/edit?usp=sharing/")
var ss = SpreadsheetApp.openByUrl(url);
var sheet = ss.getSheetByName("Sheet1");
return insert(e,sheet);
}
function doPost(e){
var url = encodeUrl("https://docs.google.com/spreadsheets/d/1IEAHcv2n33YO9d7IbfWNVLv2Hl1Q1UXveazPcgMZrMs/edit?usp=sharing/")
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1IEAHcv2n33YO9d7IbfWNVLv2Hl1Q1UXveazPcgMZrMs/edit?usp=sharing/");
var sheet = ss.getSheetByName("Sheet1");
return insert(e,sheet);
}
function insert(e,sheet) {
var scannedData = e.parameter.sdata;
var d = new Date();
var ctime = d.toLocaleString();
sheet.appendRow([scannedData,ctime]);
return ContentService
.createTextOutput("Success")
.setMimeType(ContentService.MimeType.JAVASCRIPT);
}
MainActivity.java
package com.tarbiya.scannerapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import javax.net.ssl.HttpsURLConnection;
public class MainActivity extends AppCompatActivity {
String scannedData;
Button scanBtn;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Activity activity =this;
scanBtn = (Button)findViewById(R.id.scan_btn);
scanBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
IntentIntegrator integrator = new IntentIntegrator(activity);
integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
integrator.setPrompt("Scan");
integrator.setBeepEnabled(false);
integrator.setCameraId(0);
integrator.setBarcodeImageEnabled(false);
integrator.initiateScan();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode,resultCode,data);
if(result!=null) {
scannedData = result.getContents();
if (scannedData != null) {
// Here we need to handle scanned data...
new SendRequest().execute();
}else {
}
}
super.onActivityResult(requestCode, resultCode, data);
}
public class SendRequest extends AsyncTask<String, Void, String> {
protected void onPreExecute(){}
protected String doInBackground(String... arg0) {
try{
//Enter script URL Here
URL url = new URL("https://script.google.com/macros/s/AKfycby_G_K-kmm77peQBSY6xmNZjsDcFIkDgqZwxz6e7guyte5Lxe8/exec");
JSONObject postDataParams = new JSONObject();
//int i;
//for(i=1;i<=70;i++)
// String usn = Integer.toString(i);
//Passing scanned code as parameter
postDataParams.put("sdata",scannedData);
Log.e("params",postDataParams.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line="";
while((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
}
else {
return new String("false : "+responseCode);
}
}
catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), result,
Toast.LENGTH_LONG).show();
}
}
public String getPostDataString(JSONObject params) throws Exception {
StringBuilder result = new StringBuilder();
boolean first = true;
Iterator<String> itr = params.keys();
while(itr.hasNext()){
String key= itr.next();
Object value = params.get(key);
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(key, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value.toString(), "UTF-8"));
}
return result.toString();
}
}
If you need to see more code, I can attach some more. It looks basically the same as the one in the tutorial right now.
Thank you so much for your help.
The reason you were receiving the Exception: Invalid argument: URL message is because the url you were passing to the openByUrl was not in the correct format.
If you check the documentation for the openByUrl method here, you can see the accepted format of the link.
https://docs.google.com/spreadsheets/d/abc1234567/edit
In your situation, you will have to remove the part after the /edit.
Reference
Apps Script SpreadsheetApp Class - openByUrl(url).
this is my class that receive data from server: it does not show notification
but if i take sendBroadcast(intent) and Intent out of try and catch blocks and make msg=null; it show notification but with empty message
please i need your help.
package com.example.hussienalrubaye.myapplication;
import android.app.IntentService;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class Sev_data extends IntentService {
public static boolean ServiceIsRun = false;
public Sev_data() {
super("MyWebRequestService");
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
while (ServiceIsRun) {
int id_s=0;//هنا رقم اخر رسلة وصلة التطبيق
String url0 = "http://localhost/sendapp.php?co>"+id_s;//رايط ملف الداتة من السيرفر
String msg;
try {
URL url = new URL(url0);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
msg = Stream2String(in);
in.close();
JSONObject jsonRootObject = new JSONObject(msg);
JSONArray jsonArray = jsonRootObject.optJSONArray("date");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String id= jsonObject.optString("id");
String title = jsonObject.optString("title");
String mess = jsonObject.optString("description");
///// هنا نهاية الموضوع دي اخر رسلة علي السيرفر
}
// creat new intent
intent = new Intent();
//set the action that will receive our broadcast
intent.setAction("com.example.Broadcast");
// add data to the bundle
intent.putExtra("msg", msg);
// send the data to broadcast
sendBroadcast(intent);
//delay for 50000ms
} catch (Exception e) {
}
try{
Thread.sleep(20000);
}catch (Exception ex){}
}
}
String date="";
public String Stream2String(InputStream inputStream) {
BufferedReader bureader=new BufferedReader( new InputStreamReader(inputStream));
String line ;
String Text="";
try{
while((line=bureader.readLine())!=null) {
Text+=line;
}
inputStream.close();
}catch (Exception ex){}
return Text;
}
}
and this is receiver class:
package com.example.doblist.mydobservice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// get the bundles in the message
final Bundle bundle = intent.getExtras();
// check the action equal to the action we fire in broadcast,
if ( intent.getAction().equalsIgnoreCase("com.example.Broadcast"))
//read the data from the intent
{ NewMessageNotification notfilyme= new NewMessageNotification();
notfilyme.notify(context,bundle.getString("msg"),223);}
// Toast.makeText(context,bundle.getString("msg"),Toast.LENGTH_LONG).show();
}
}
i add all AndroidManifest permission all things well but it dose not show notification
I want to know. is the cod that get data from server true or not
Hello guys so i'm having difficult in changing this classes that i've created to httpurlConnection. i've seraced the web and im not familiar at all with the httpUrlConnection
App flow:
coming to MainActivity => OnTokenAcuired => GetCokie => Auth
then i have an httpPostRequest
MainActivity:
package com.ap2.demo.comunication;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import com.ap2.demo.R;
import com.ap2.demo.general.SplashActivity;
import org.apache.http.impl.client.DefaultHttpClient;
import java.util.ArrayList;
public class MainActivity extends Activity {
AccountManager accountManager;
private Account[] accounts;
Spinner spinner;
public static DefaultHttpClient httpClient = new DefaultHttpClient();
Account account;
public static String email = "";
ImageView img;
public static boolean enteredOnce = false;
public static String uniqueIDPhone = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
accountManager = AccountManager.get(getApplicationContext());
// assembling all gmail accounts
accounts = accountManager.getAccountsByType("com.google");
// add all gmail accounts :
ArrayList<String> accountList = new ArrayList<String>();
for (Account account : accounts) {
accountList.add(account.name);
}
// setting spinner to be viewed
spinner = (Spinner) findViewById(R.id.account);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, accountList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
img = (ImageView) findViewById(R.id.splash_door);
//Button startAuth = (Button) findViewById(R.id.startAuth);
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
spinner = (Spinner) findViewById(R.id.account);
account = accounts[spinner.getSelectedItemPosition()];
email = account.name;
// getIntent().putExtra("task", 1);
accountManager.getAuthToken(account, "ah", null, false,
new OnTokenAcquired(httpClient, MainActivity.this), null);
Intent intent = new Intent(MainActivity.this, SplashActivity.class);
startActivity(intent);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK) {
accountManager.getAuthToken(account, "ah", null, false,
new OnTokenAcquired(httpClient, MainActivity.this), null);
}
else if(resultCode == RESULT_CANCELED){
// user canceled
}
}
}
OnTokenAcquired:
package com.ap2.demo.comunication;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import com.ap2.demo.enumPackage.Constants;
import org.apache.http.impl.client.DefaultHttpClient;
/**
* Created by Daniel on 19-Jun-15.
*/
/*the result for the auth token request is returned to your application
via the Account Manager Callback you specified when making the request.
check the returned bundle if an Intent is stored against the AccountManager.KEY_INTENT key.
if there is an Intent then start the activity using that intent to ask for user permission
otherwise you can retrieve the auth token from the bundle.*/
public class OnTokenAcquired implements AccountManagerCallback<Bundle> {
private static final int USER_PERMISSION = 989;
private DefaultHttpClient httpclient;
Activity activity;
public OnTokenAcquired(DefaultHttpClient httpclient, Activity activity)
{
this.httpclient = httpclient;
this.activity = activity;
}
#Override
public void run(AccountManagerFuture<Bundle> result) {
Bundle bundle;
try {
bundle = (Bundle) result.getResult();
if (bundle.containsKey(AccountManager.KEY_INTENT)) {
Intent intent = bundle.getParcelable(AccountManager.KEY_INTENT);
intent.setFlags(intent.getFlags() & ~Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivityForResult(intent, USER_PERMISSION);
} else {
setAuthToken(bundle);
}
}
catch(Exception e){
e.printStackTrace();
}
}
//using the auth token and ask for a auth cookie
protected void setAuthToken(Bundle bundle) {
String authToken = bundle.getString(AccountManager.KEY_AUTHTOKEN);
new GetCookie(httpclient, Constants.SERVER_REQUESTS.MY_APP_ID, activity.getBaseContext()).execute(authToken);
}
}
package com.ap2.demo.comunication;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import com.ap2.demo.enumPackage.Constants;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;
import java.io.ByteArrayOutputStream;
/**
* Created by Daniel on 19-Jun-15.
*/
public class GetCookie extends AsyncTask<String, Void, Boolean> {
String appId;
HttpParams params;
private HttpResponse response;
Context context;
private DefaultHttpClient httpclient;
public GetCookie(DefaultHttpClient httpclient, String appId, Context context)
{
this.httpclient = httpclient;
params = httpclient.getParams();
this.appId = appId;
this.context = context;
}
protected Boolean doInBackground(String... tokens) {
try {
// Don't follow redirects
params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);
HttpGet httpGet = new HttpGet("http://" + appId
+ ".appspot.com/_ah/login?continue=http://" + appId + ".appspot.com/&auth=" + tokens[0]);
response = httpclient.execute(httpGet);
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
if(response.getStatusLine().getStatusCode() != 302){
// Response should be a redirect
return false;
}
//check if we received the ACSID or the SACSID cookie, depends on http or https request
for(Cookie cookie : httpclient.getCookieStore().getCookies()) {
if(cookie.getName().equals("ACSID") || cookie.getName().equals("SACSID")){
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
cancel(true);
} finally {
params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
}
return false;
}
protected void onPostExecute(Boolean result)
{
new Auth(httpclient, context).execute(Constants.SERVER_REQUESTS.LOGIN);
}
}
package com.ap2.demo.comunication;
import android.content.Context;
import android.os.AsyncTask;
import android.telephony.TelephonyManager;
import android.widget.Toast;
import com.ap2.demo.R;
import com.ap2.demo.enumPackage.Constants;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
/**
* Created by Daniel on 19-Jun-15.
*/
public class Auth extends AsyncTask<String, Void, Boolean> {
private DefaultHttpClient httpclient;
private HttpResponse response;
private String content = null;
Context context;
public Auth(DefaultHttpClient httpclient, Context context)
{
this.httpclient = httpclient;
this.context = context;
}
protected Boolean doInBackground(String... urls) {
try {
HttpGet httpGet = new HttpGet(urls[0]);
response = httpclient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
content = out.toString();
return true;
}
} catch (Exception e) {
e.printStackTrace();
cancel(true);
}
return false;
}
//display the response from the request above
protected void onPostExecute(Boolean result) {
if (content != null) {
try {
System.out.print(result);
JSONObject obj = new JSONObject(content);
String status = obj.getString(Constants.LOGIN_SERVICE.STATUS);
if (status.equals(Constants.LOGIN_SERVICE.LOGIN_STATUS_OF_USER)) {
Toast.makeText(context, R.string.user_already_logged_in_status,
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, R.string.welcome_message,
Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(context, R.string.failed_to_login + content,
Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(context, R.string.could_not_loged_to_server,
Toast.LENGTH_LONG).show();
}
}
}
now notice im using the same httpclient because of the auth and cockie:
package com.ap2.demo.channels;
import android.app.Activity;
import android.os.AsyncTask;
import com.ap2.demo.comunication.MainActivity;
import com.ap2.demo.enumPackage.Constants;
import com.ap2.demo.main_activity.MapWithMarkers;
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.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Daniel on 30-Jun-15.
*/
public class ServerRequestAddChannel extends AsyncTask<String, String, String> {
Activity activity;
String name;
public ServerRequestAddChannel(Activity activity, String name) {
this.activity = activity;
this.name = name;
}
#Override
protected String doInBackground(String... params) {
HttpPost httppost = new HttpPost(params[0]);
try {
// i have name and path only left id
int idCounter = MapWithMarkers.id_counter++;
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
String name_of_channel = name;
if (name.equals(Constants.REVIEWS_CHANNEL.NAME)) {
// add special id to reviews channel
nameValuePairs.add(new BasicNameValuePair(Constants.REVIEWS_CHANNEL.ID, Constants.REVIEWS_CHANNEL.ID));
} else {
name_of_channel = name + Integer.toString(idCounter);
// taking off all free space for unique id
name_of_channel = name_of_channel.replaceAll(" ","");
nameValuePairs.add(new BasicNameValuePair(Constants.CHANNEL_REQUESTS.CHANNEL_TAG_ID, name_of_channel));
}
nameValuePairs.add(new BasicNameValuePair(Constants.CHANNEL_REQUESTS.CHANNEL_TAG_NAME, name));
nameValuePairs.add(new BasicNameValuePair(Constants.CHANNEL_REQUESTS.CHANNEL_TAG_ICON, ""));
// adding the channel to my new list
if (!name_of_channel.equals(Constants.REVIEWS_CHANNEL.NAME)) {
MapWithMarkers.channels_map.put(name_of_channel, new ChannelItem(name_of_channel, "", name));
MapWithMarkers.my_subscriptions.add(name_of_channel);
}
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = MainActivity.httpClient.execute(httppost);
HttpEntity entity = response.getEntity();
String text = getASCIIContentFromEntity(entity);
return response.getStatusLine().getReasonPhrase().toString();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
return null;
}
protected void onPostExecute(String result) {
((AddChannelActivity) activity).moveToNextIntent();
}
protected String getASCIIContentFromEntity(HttpEntity entity)
throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n > 0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n > 0)
out.append(new String(b, 0, n));
}
return out.toString();
}
}
please help..
I have an async task that when data is loaded it also set an onClick for a star rating bar.
When I user clicks the star rating bar, I want to load a new fragment. I am trying this:
package com.example.mike.beerportfoliomaterial;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Mike on 6/22/15.
*/
public class getReviewToRateJSON extends AsyncTask<String, Void, String> {
Context c;
String noteWriter;
String noteID;
private ProgressDialog Dialog;
public getReviewToRateJSON(Context context)
{
c = context;
Dialog = new ProgressDialog(c);
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPreExecute() {
Dialog.setMessage("Getting A Taste Note");
Dialog.setTitle("Loading");
Dialog.show();
}
protected void onPostExecute(String result){
//decode json here
try{
JSONObject jsonObject = new JSONObject(result);
noteWriter = jsonObject.getString("reviewer");
String beer = jsonObject.getString("beer");
noteID = jsonObject.getString("noteID");
String noteToRead = jsonObject.getString("note");
TextView note = (TextView) ((Activity) c).findViewById(R.id.reviewToRate);
note.setText(noteToRead);
}
catch(Exception e){
}
//todo: url to send rating too
addListenerOnRatingBar(c);
Dialog.dismiss();
}
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
private void addListenerOnRatingBar(final Context view) {
RatingBar ratingBar = (RatingBar) ((Activity) view).findViewById(R.id.reviewRatingBar);
ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromUser) {
//next async task to update online database
float stars = ratingBar.getRating();
String s = Float.toString(stars);
//get user id
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);
String userName = prefs.getString("userName", null);
final String userID = prefs.getString("userID", null);
String url = "myURL;
//async task to update rating in database
new AddNoteRate(c).execute(url);
Fragment Fragment_four;
FragmentManager man= ((Activity) view).getSupportFragmentManager();
FragmentTransaction tran = man.beginTransaction();
Fragment_four = new RateReviews();
tran.replace(R.id.main, Fragment_four);//tran.
tran.addToBackStack(null);
tran.commit();
}
});
}
}
My big issue is I ca not get it to load a new fragment on these lines:
Fragment Fragment_four;
FragmentManager man= ((Activity) view).getSupportFragmentManager();
FragmentTransaction tran = man.beginTransaction();
Fragment_four = new RateReviews();
tran.replace(R.id.main, Fragment_four);//tran.
tran.addToBackStack(null);
tran.commit();
I get a "cannot resolve method" error on this line:
FragmentManager man= ((Activity) view).getSupportFragmentManager();
I also tried to change getSupportFragmentManager to getFragmentManager, neith worked.
Activity does not have a getSupportFragmentManager function. The FragmentActivity class in the v4 support library does. Cast it as that instead, and make sure your actual Activity derives from that rather than from Activity.
Side note- this may fail anyway. A Context is not necessarily an Activity. In fact it will frequently get wrapped in a ContextWrapper or ContextThemeWrapper. In either case this code will fail.
You should make a constructor in asynctask, passing activity as parameter.
AsyncTask.class
public class AsyncTaskExample extends AsyncTask<String, Integer, String>
{
Activity atv;
public AsyncTaskExample (Activity atv)
{
this.atv = atv;
}
#Override
protected void onPostExecute(String result) // contain according to regCheck.php
{
FragmentManager fragmentManager;
fragmentManager = atv.getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.main, Fragment_four)
.commit();
}
}
Fragment passing in
AsyncTaskExample task = new AsyncTaskExample( getActivity() );
package com.example.friendfinder;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class login extends Activity implements OnClickListener{
String APIurl = "http://friendfinder.hostzi.com/ws/";
Button btnlogin;
TextView login_user;
TextView login_pass;
TextView tv;
JSONObject jObject;
AlertDialog.Builder builder;
AlertDialog alert;
ProgressDialog progressDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
start();
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_entrar:
if (checkStatus()) {
progressDialog.show();
new Thread(new Runnable() {
public void run() {
try {
jObject = new JSONObject(getJSON("login.php?email="
+ login_user.getText().toString()
+ "&password="
+ login_pass.getText().toString()));
tv.setText(jObject.toString());
Log.e("JSON", jObject.toString());
if (jObject.getString("success").equalsIgnoreCase(
"true")) {
progressDialog.dismiss();
confirm();
} else if (jObject.getString("success")
.equalsIgnoreCase("false")) {
login.this.runOnUiThread(new Runnable() {
#Override
public void run() {
progressDialog.dismiss();
builder.setMessage("O inicio de sessão falhou, verifica os teus dados.");
alert = builder.create();
alert.show();
}
});
login.this.runOnUiThread(null);
} else {
login.this.runOnUiThread(new Runnable() {
#Override
public void run() {
progressDialog.dismiss();
builder.setMessage("O inicio de sessão falhou, verifica os teus dados.");
alert = builder.create();
alert.show();
}
});
login.this.runOnUiThread(null);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
else{
builder.setMessage("Não existe de momento nenhuma conexão à Internet! O ínicio de sessão é impossivel de realizar");
alert = builder.create();
alert.show();
}
}
}
public void start(){
login_user = (TextView) findViewById(R.id.login_user);
login_pass = (TextView) findViewById(R.id.login_pass);
tv = (TextView) findViewById(R.id.tv);
btnlogin = (Button) findViewById(R.id.btn_entrar);
btnlogin.setOnClickListener(this);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("A iniciar sessão...");
builder = new AlertDialog.Builder(login.this);
builder.setCancelable(false);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
}
public void confirm(){
Intent i = new Intent(login.this, maps.class);
startActivity(i);
finish();
}
public String getJSON(String rurl) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(APIurl + rurl);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
public boolean checkStatus() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
}
LogCat
http://pastebin.com/0xVv2pBR
When i click the button to login the app crashes and i realy can't understand what is wrong, if you need more information just ask me. If you know how to resolve help me please.
Thanks
logs says
"02-06 18:50:47.785: I/Choreographer(874): Skipped 41 frames! The application may be doing too much work on its main thread"
if you are new to Android you must learn to implement AsyncTask in your Activity. You are not suppose to use webservice or http communication in main/UI thread. here i found Tutorial to implement AsyncTask please learn it will solve your problem.