How can i get the source page in android studio? I tried many codes. Like :
Code 1:
Code:
try{
URL yahoo = new URL(<mylink>);
BufferedReader in = new BufferedReader(new InputStreamReader(yahoo.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
catch(MalformedURLException e){
Toast.makeText(this, e.getMessage() + " - 1" , Toast.LENGTH_LONG).show();
}
catch(IOException e){
Toast.makeText(this, e.getMessage() + " - 2" , Toast.LENGTH_LONG).show();
}
catch(Exception e){
Toast.makeText(this, e.getMessage() + " - 3" , Toast.LENGTH_LONG).show();
}
Code 2 :
Code:
private static String getUrlSource(String url) throws IOException {
URL yahoo = new URL(url);
URLConnection yc = yahoo.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream(), "UTF-8"));
String inputLine;
StringBuilder a = new StringBuilder();
while ((inputLine = in.readLine()) != null)
a.append(inputLine);
in.close();
return a.toString();
}
And many others. All of them throws exception.. Why?
PS : I also have "<uses-permission android:name="android.permission.INTERNET" /> " in manifest file.
Try looking at the code examples for jsoup library.
Sent from my ASUS_Z00AD using XDA Free mobile app
Related
I want to write a text file. But I am not sure how writing down works in Android. Here is my code:
Code:
EditText textbox1 = (EditText) findViewById(R.id.editText);
EditText textbox2 = (EditText) findViewById(R.id.editText2);
EditText textbox3 = (EditText) findViewById(R.id.editText3);
public void writeToPhonebook(View v) {
Button button=(Button) v;
try {
File fajl = new File("phonebook.txt");
Writer writer;
writer= new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fajl, true), "UTF-8"));
writer.append(textbox1.getText() + "\t" + textbox2.getText() + "\t" + textbox3.getText());
writer.write("\r\n");
writer.close();
textbox1.setText("");
textbox2.setText("");
textbox3.setText("");
textbox1.requestFocus();
}
catch (IOException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
ex.printStackTrace();
}
}
can I just leave phonebook.txt or need to put something else? Because with this code apk can't even start on emulator.
OK I done this previus. I now need to load data from text file into table (table layout with 3 columns). Is it possible for application to determine number of needed rows without me adding certain number. Because that data will be changed.
You need permissions to write a file, you set them in the AndroidManifest xml (Every Android Studio project has their own manifest, set it in your project)
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Then you need to open a file for input/output... You do this in whatever.java
Code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import android.util.Log;
public class FileOperations {
public FileOperations() {
}
public Boolean write(String fname, String fcontent){
try {
String fpath = "/sdcard/"+fname+".txt";
File file = new File(fpath);
// If file does not exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(fcontent);
bw.close();
Log.d("Suceess","Sucess");
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public String read(String fname){
BufferedReader br = null;
String response = null;
try {
StringBuffer output = new StringBuffer();
String fpath = "/sdcard/"+fname+".txt";
br = new BufferedReader(new FileReader(fpath));
String line = "";
while ((line = br.readLine()) != null) {
output.append(line +"n");
}
response = output.toString();
} catch (IOException e) {
e.printStackTrace();
return null;
}
return response;
}
}
What is easier to display data from text file in: TableLayout or ViewList? If not sure total number of rows? Is there something for scrooling through it if can't fit the screen?
Scrollview
Grimspiller said:
What is easier to display data from text file in: TableLayout or ViewList? If not sure total number of rows? Is there something for scrooling through it if can't fit the screen?
Click to expand...
Click to collapse
1) Yes. Android provide scrollview to scroll on your query.
A. Horizontal scrollview
B. Vertical Scrollview.
Also you can you onTextwatcher() to check if the field size increase , onAfterTextchanged() method you can resize the box is.
private final TextWatcher passwordWatcher = new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
textView.setVisibility(View.VISIBLE);
}
public void afterTextChanged(Editable s) {
if (s.length() == 0) {
textView.setVisibility(View.GONE);
} else{
textView.setText("You have entered : " + passwordEditText.getText());
}
}
};
I found this tutorial for multicolumn ListView on techlovejump.com ,but data for it is hardcoded. I am not sure is it suitable for dynamic data adding from text file.
Dynamic Data
Grimspiller said:
I found this tutorial for multicolumn ListView on techlovejump.com ,but data for it is hardcoded. I am not sure is it suitable for dynamic data adding from text file.
Click to expand...
Click to collapse
hey, As you see on after afterTextChanged(Editable s)
You can again call your table structure code to design it as per size.
I think you should try it once.
Share some amount of code if you find it difficult. I will help you afterTextChanged(Editable s).
I don't need to write text but to read it. Can you look at this code and tell me what is the problem? It can't find the file.
Code:
void showData(){
File fajl = new File("phonebook.txt");
try {
BufferedReader br = new BufferedReader(new FileReader(fajl));
String line;
try {
while ((line = br.readLine()) != null) {
TableRow tr = new TableRow(this);
tr.setLayoutParams(new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT));
TextView im = new TextView(this);
im.setText(line);
im.setTextColor(Color.BLACK);
im.setLayoutParams(new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT));
tr.addView(im);
tablel.addView(tr, new TableLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT));
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
button2.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
showData();
}
});
I have added to xml TableLayout and one row as header.
I use this for writing to text file:
Code:
button.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
try {
FileOutputStream fos = openFileOutput("phonebook.txt", Context.MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fos);
osw.append(textbox1.getText().toString() + "\t" + textbox2.getText().toString() + "\t" + textbox3.getText().toString());
osw.write("\r\n");
osw.close();
textbox1.setText("");
textbox2.setText("");
textbox3.setText("");
textbox1.requestFocus();
} catch (IOException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
ex.printStackTrace();
}
}
});
Debbuger says it's writting file and lines just fine. But why I can't read it?
It creates "files" folder inside my app folder. And inside files it is phonebook.txt.
Hi there,
I have an issue with writing my app. I want to obtain the data (as shown below) and get the corresponding value from it. When I run my app on the emulator it crashes when I click the button, precisely on this line:
Code:
JSONObject jsonObject = json.getJSONObject(0);
Can someone at least, please skim through and let me know what I could be doing wrong. It must be something simple, because I am not trying to break into CIA from my phone.
This is a data from the link:
HTML:
// [ { "id": "304466804484872" ,"t" : "GOOG" ,"e" : "NASDAQ" ,"l" : "759.66" ,"l_fix" : "759.66" ,"l_cur" : "759.66" ,"s": "0" ,"ltt":"4:00PM EDT" ,"lt" : "Sep 9, 4:00PM EDT" ,"lt_dts" : "2016-09-09T16:00:03Z" ,"c" : "-15.66" ,"c_fix" : "-15.66" ,"cp" : "-2.02" ,"cp_fix" : "-2.02" ,"ccol" : "chr" ,"pcls_fix" : "775.32" } ]
Here is my class:
Code:
public JSONArray getJson(String url){
// Read response to string
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL Url = new URL(url);
connection = (HttpURLConnection) Url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line+"\n");
}
is.close();
result = sb.toString();
} catch(Exception e) {
return null;
}
// Convert string to object
try {
String token[] = result.split("//");
JSONArray jarr = new JSONArray (token[1]);
} catch(JSONException e){
return null;
}
return jarr;
}
This is how I use it on a click of a button:
Code:
quotebutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Constructing a URL
String urlprefix = "http://finance.google.com/finance/info?client=ig&q=";
String Symbol = editTextSymbol.getText().toString();
String Exchange = editTextExchange.getText().toString();
String url = urlprefix + Exchange + ":" + Symbol;
JSONArray json = getJson(url);
try {
JSONObject jsonObject = json.getJSONObject(0);
String id = jsonObject.getString("id");
EditTextQuoteTime.setText(id);
} catch (JSONException e){
EditTextQuoteTime.setText("ERROR");
}
//try {
// String id = json.getString("id");
// EditTextQuoteTime.setText(id);
//} catch (JSONException e){
// EditTextQuoteTime.setText("ERROR");
// }
}
});
I know I may have asked a question that is widely available online, but most of the posts are from the time before which the libraries were updated and parsing from the URL changed. Most of the posts are slightly different and I feel I am missing something.
I think I have a main problem with decoding the actual JSON string which is shown in the HTML above. I don't know how to omit the first few signs and then get my string from there. Can anyone help, please?
Hi Folks.
I am new to android studio and object oriented programming in general so apologies if this is obvious but I cannot get my head round it. I have a small xml web server and I can connect to it and send data to it and I can also read it back and view it in the monitor. I want to do xml parsing on it but cannot get it to work.
Below is the xml server being displayed in the android monitor and is from the line "System.out.println(output);"
The response is saved from a string but I think I need it in a different format to do a pull parser on it. The program basically prints this string and then crashes. What is the best way to parse my data? Any help would be really appreciated.
<TITLE>GET test page</TITLE>
05-16 20:19:50.499 13394-14092/com.example.mark.gps_to_server I/System.out: </HEAD>
05-16 20:19:50.499 13394-14092/com.example.mark.gps_to_server I/System.out: <BODY>
05-16 20:19:50.499 13394-14092/com.example.mark.gps_to_server I/System.out: <H1>LED Control</H1>
05-16 20:19:50.499 13394-14092/com.example.mark.gps_to_server I/System.out: <a href="/?nnn" >ON</a>
05-16 20:19:50.499 13394-14092/com.example.mark.gps_to_server I/System.out: <a href="/?fff" >OFF</a>
05-16 20:19:50.499 13394-14092/com.example.mark.gps_to_server I/System.out: <IFRAME name=inlineframe style="display:none" >
05-16 20:19:50.519 13394-14092/com.example.mark.gps_to_server I/System.out: </IFRAME>
05-16 20:19:50.519 13394-14092/com.example.mark.gps_to_server I/System.out: <H1>Status On Now</H1>
05-16 20:19:50.529 13394-14092/com.example.mark.gps_to_server I/System.out: <H2> test</H2>
Click to expand...
Click to collapse
The code:
Code:
public class HTTPRequestTask extends AsyncTask<String , Void, String > {
@Override
protected String doInBackground(String... args) {
String IP = args[0];
System.out.println(IP);
try {
URL url = new URL(IP);
XmlPullParser recievedData = XmlPullParserFactory.newInstance().newPullParser();
recievedData.setInput(url.openStream(),null);
System.setProperty("http.keepAlive", "false");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
XmlPullParser parser = Xml.newPullParser();
parser.setInput(new StringReader(output));
System.out.println("doc");
System.out.println(parser);
System.out.println("Disconnecting\n");
conn.disconnect();
//System.out.println(recievedData);
processRecievedData(recievedData);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
return null;
}
private int processRecievedData(XmlPullParser xmlData) {
int recordsFound = 0; // Find values in the XML records
int eventType = -1;
String appId = ""; // Attributes
String itemId = "";
String timeStamp = ""; String data = ""; // Text int eventType = -1;
while (eventType != XmlResourceParser.END_DOCUMENT) {
String tagName = xmlData.getName();
switch (eventType) {
case XmlResourceParser.START_TAG: // Start of a record, so pull values encoded as attributes.
if (tagName.equals("Version")) {
System.out.println("yes");
appId = xmlData.getAttributeValue(null, "Model");
itemId = xmlData.getAttributeValue(null, "vendor_id");
timeStamp = xmlData.getAttributeValue(null, "timestamp");
data = "";
}
System.out.println("no");
break;
// Grab data text (very simple processing)
// NOTE: This could be full XML data to process.
case XmlResourceParser.TEXT:
data += xmlData.getText();
break;
case XmlPullParser.END_TAG:
if (tagName.equals("record")) {
recordsFound++;
//publishProgress(appId, itemId, data, timeStamp);
}
break;
}
//eventType = xmlData.next();
}
// Handle no data available: Publish an empty event.
if (recordsFound == 0) { publishProgress();
}
Log.i(TAG, "Finished processing "+recordsFound+" records.");
return recordsFound;
}
protected void onProgressUpdate(String... values) {
if (values.length == 0) {
Log.i(TAG, "No data downloaded");
}
if (values.length == 4) {
String appId = values[0];
String itemId = values[1];
String data = values[2];
String timeStamp = values[3];
// Log it
Log.i(TAG, "AppID: " + appId + ", Timestamp: " + timeStamp);
Log.i(TAG, " ItemID: " + itemId + ", Data: " + data);
// Pass it to the application handleNewRecord(itemId, data); }
//super.onProgressUpdate(values);
}
}
Thanks.
Probably you should use 3rd party library to parse XML from your web server. This will significantly reduce the code and improve performance. Of course, before parsing xml, you should download the data.
Personal prefference
I prefer the document (DOM) parsing. I think DOM parsing is more object oriented.
Whats the error in the log?
this works for me:
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
} catch (IOException e) {
e.printStackTrace();
}
StringBuffer sb = new StringBuffer("");
String line="";
while ((line = in.readLine()) != null) {
sb.append(line);
}
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
String sb_string = sb.toString();
Document return_doc = null;
if(sb_string.equals(0))
{
}
else {
DocumentBuilder db = null;
try {
db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(sb_string));
try {
return_doc = db.parse(is);
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Please note! It took me a while before i could get attributes and knew the difference between nodes and elements.
this line of thought will require you to gain more information how to work with documents which might get frustration but in the end it might be beneficial.
hi my app is ood but when i hav not internet and cant load data from my database
my app will be force close
my error is in emulatur
130 - AsyncHttpClient.getDefaultInstance().executeString(post, new AsyncHttpClient.StringCallback() {
and
153- if(!result.equals("")){
in this java activity
HTML:
package com.smartapp.soton;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.CardView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.afollestad.materialdialogs.MaterialDialog;
import com.baoyz.widget.PullRefreshLayout;
import com.koushikdutta.async.http.AsyncHttpClient;
import com.koushikdutta.async.http.AsyncHttpPost;
import com.koushikdutta.async.http.AsyncHttpResponse;
import com.koushikdutta.async.http.body.MultipartFormDataBody;
import com.koushikdutta.async.http.socketio.ExceptionCallback;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
public class Frag_Banners_All extends Fragment {
// Development by SmartMob (Manager : Mohammad Mokhles)
View v ;
Context context ;
GridView gridView ;
public List<HashMap<String , Object>> hash_all ;
String[] items ;
Ad ad ;
int preLast ;
int page = 0 ;
View row ;
ImageView row_list_img1 ;
TextView row_list_title , row_list_price , row_list_time ;
CardView row_list_card ;
PullRefreshLayout refresh ;
[user=3869344]@nullable[/user]
[user=439709]@override[/user]
public View onCreateView(LayoutInflater inflater, [user=3869344]@nullable[/user] ViewGroup container, [user=3869344]@nullable[/user] Bundle savedInstanceState) {
v = inflater.inflate(R.layout.frag_banners_all,container,false);
context = v.getContext();
hash_all = new ArrayList<>();
items = new String[hash_all.size()];
ad = new Ad();
gridView = (GridView)v.findViewById(R.id.grid_all);
gridView.setAdapter(ad);
gridView.setOnScrollListener(new AbsListView.OnScrollListener() {
[user=439709]@override[/user]
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
[user=439709]@override[/user]
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if(totalItemCount>=10){
final int lastItem = firstVisibleItem + visibleItemCount ;
if(lastItem == totalItemCount){
if(preLast != lastItem){
preLast = lastItem ;
page = page + 1 ;
try {
get_banners(page);
}catch (Exception e){
e.printStackTrace();
}
}
}
}
}
});
page = 0 ;
preLast = 0 ;
CheckNet();
refresh = (PullRefreshLayout)v.findViewById(R.id.refresh);
refresh.setOnRefreshListener(new PullRefreshLayout.OnRefreshListener() {
[user=439709]@override[/user]
public void onRefresh() {
page = 0 ;
preLast = 0 ;
CheckNet();
}
});
return v;
}
private void get_banners(final int pages){
MainActivity.wait.show();
AsyncHttpPost post = new AsyncHttpPost(
"this is my linke i removed"
);
post.setTimeout(5000);
MultipartFormDataBody body = new MultipartFormDataBody();
body.addStringPart("City",MainActivity.sp.getString("City",null));
body.addStringPart("Cate","all");
body.addStringPart("Page", String.valueOf(pages));
post.setBody(body);
try{
AsyncHttpClient.getDefaultInstance().executeString(post, new AsyncHttpClient.StringCallback() {
[user=439709]@override[/user]
public void onCompleted(final Exception e, AsyncHttpResponse source, final String result) {
CheckNet();
if(e != null){
MainActivity.activity.runOnUiThread(new Runnable() {
[user=439709]@override[/user]
public void run() {
try{
refresh.setRefreshing(false);
}catch (Exception e){
e.printStackTrace();
}
MainActivity.wait.dismiss();
Toast.makeText(MainActivity.activity, "خطا در برقراری اتصال با سرور !", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
});
}
if(!result.equals("")){
MainActivity.activity.runOnUiThread(new Runnable() {
[user=439709]@override[/user]
public void run() {
MainActivity.wait.dismiss();
if(page==0){
hash_all.clear();
}
items.clone();
try {
JSONArray jsonArray = new JSONArray(result);
for (int i = 0 ;i<jsonArray.length();i++){
JSONObject object = jsonArray.getJSONObject(i);
HashMap<String , Object> hash_add = new HashMap<String, Object>();
hash_add.put("ID",object.getString("ID"));
hash_add.put("Username",object.getString("Username"));
hash_add.put("Title",object.getString("Title"));
hash_add.put("Descript",object.getString("Descript"));
hash_add.put("Price",object.getString("Price"));
hash_add.put("Tell",object.getString("Tell"));
hash_add.put("Email",object.getString("Email"));
hash_add.put("City",object.getString("City"));
hash_add.put("Cate",object.getString("Cate"));
hash_add.put("Img1",object.getString("Img1"));
hash_add.put("Img2",object.getString("Img2"));
hash_add.put("Img3",object.getString("Img3"));
hash_add.put("Date",object.getString("Date"));
hash_all.add(hash_add);
items = new String[hash_all.size()];
}
ad.notifyDataSetChanged();
refresh.setRefreshing(false);
}catch (Exception e){
e.printStackTrace();
}
}
});
}
}
});
}catch (Exception e){
e.printStackTrace();
}
}
public class Ad extends ArrayAdapter<String>{
private LayoutInflater inflater = null ;
public Ad(){
super(context,R.layout.row_list);
inflater = (LayoutInflater)MainActivity.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
[user=439709]@override[/user]
public int getCount() {
return items.length;
}
[user=923100]@Nonnu[/user]ll
[user=439709]@override[/user]
public View getView(int position, View convertView, ViewGroup parent) {
row = convertView ;
if(convertView == null){
row = inflater.inflate(R.layout.row_list,parent,false);
}
row_list_img1 = (ImageView)row.findViewById(R.id.row_list_img1);
row_list_title = (TextView) row.findViewById(R.id.row_list_title);
row_list_price = (TextView)row.findViewById(R.id.row_list_price);
row_list_time = (TextView)row.findViewById(R.id.row_list_time);
row_list_card = (CardView) row.findViewById(R.id.row_list_card);
final HashMap<String , Object> hash_get = (HashMap<String , Object>) hash_all.get(position);
row_list_title.setText(hash_get.get("Title").toString());
row_list_price.setText(hash_get.get("Price").toString()+" تومان");
if(Integer.parseInt(hash_get.get("Date").toString())<=59){
if(hash_get.get("Date").toString().equals("0") || hash_get.get("Date").toString().equals("1")){
row_list_time.setText("همین الان");
}else {
row_list_time.setText(hash_get.get("Date").toString()+" دقیقه پیش");
}
}else if(Integer.parseInt(hash_get.get("Date").toString())>=60 && Integer.parseInt(hash_get.get("Date").toString())<=1439){
int h = Integer.parseInt(hash_get.get("Date").toString())/60;
row_list_time.setText(h+" ساعت پیش");
}else if(Integer.parseInt(hash_get.get("Date").toString())>=1440 && Integer.parseInt(hash_get.get("Date").toString())<=43199){
int hh = Integer.parseInt(hash_get.get("Date").toString())/60/24;
row_list_time.setText(hh+" روز پیش");
}else if(Integer.parseInt(hash_get.get("Date").toString())>=43200 && Integer.parseInt(hash_get.get("Date").toString())<=518339){
int hhh = Integer.parseInt(hash_get.get("Date").toString())/60/24/30;
row_list_time.setText(hhh+" ماه پیش");
}else if(Integer.parseInt(hash_get.get("Date").toString())>=518340){
int hhhh = Integer.parseInt(hash_get.get("Date").toString())/60/24/30/12;
row_list_time.setText(hhhh+" سال پیش");
}
Picasso.with(MainActivity.activity)
.load(hash_get.get("Img1").toString())
.placeholder(R.mipmap.ic_launcher)
.into(row_list_img1);
row_list_card.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
Intent intent = new Intent(MainActivity.activity,Detail_Banners.class);
intent.putExtra("ID",hash_get.get("ID").toString());
intent.putExtra("Username",hash_get.get("Username").toString());
intent.putExtra("Title",hash_get.get("Title").toString());
intent.putExtra("Descript",hash_get.get("Descript").toString());
intent.putExtra("Price",hash_get.get("Price").toString());
intent.putExtra("Tell",hash_get.get("Tell").toString());
intent.putExtra("Email",hash_get.get("Email").toString());
intent.putExtra("City",hash_get.get("City").toString());
intent.putExtra("Cate",hash_get.get("Cate").toString());
intent.putExtra("Img1",hash_get.get("Img1").toString());
intent.putExtra("Img2",hash_get.get("Img2").toString());
intent.putExtra("Img3",hash_get.get("Img3").toString());
intent.putExtra("Date",hash_get.get("Date").toString());
startActivity(intent);
}
});
return row;
}
}
private void saeed(){
}
private void CheckNet(){
boolean connect = false ;
ConnectivityManager connectivityManager = (ConnectivityManager)MainActivity.activity.getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED
|| connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED){
connect = true ;
}else {
connect = false ;
}
if(connect==true){
try {
get_banners(page);
}catch (Exception e){
e.printStackTrace();
}
}else {
new MaterialDialog.Builder(MainActivity.activity)
.title("عدم اتصال به اینترنت")
.content("لطفا اتصال به اینترنت خود را بررسی کنید")
.positiveText("بررسی مجدد")
.negativeText("خروج")
.callback(new MaterialDialog.ButtonCallback() {
[user=439709]@override[/user]
public void onNegative(MaterialDialog dialog) {
super.onNegative(dialog);
MainActivity.activity.finish();
}
[user=439709]@override[/user]
public void onPositive(MaterialDialog dialog) {
super.onPositive(dialog);
CheckNet();
}
})
.show();
}
}
// Development by SmartMob (Manager : Mohammad Mokhles)
}
althing is ok but when i havent internet connection it will be force close
Have you ever tried to extend your favorite app with new features using Xposed, but were shocked halfway that your hooked app doesn't declare a permission in AndroidManifest ? And then you spent infinite hours on the internet trying to solve this frustrating problem, you decided to use services and an external intent, but you found out that it was not convenient, and finally you gave up...
So you are like me, who wasted hours looking for a solution, until I figured out how to do it myself. Here's a snippet to save time for future Xposed enthusiasts. Put this code snippet in handleLoadPackage
Java:
// Hook will only patch System Framework
if (!lpparam.packageName.equals("android")) return;
String targetPkgName = "com.example.app"; // Replace this with the target app package name
String[] newPermissions = new String[] { // Put the new permissions here
"android.permission.INTERNET",
"android.permission.ACCESS_NETWORK_STATE"
};
String grantPermissionsMethod = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
grantPermissionsMethod = "restorePermissionState";
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.S_V2) {
XposedBridge.log("[WARNING] THIS HOOK IS NOT GUARANTEED TO WORK ON ANDROID VERSIONS NEWER THAN ANDROID 12");
}
} else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.P) {
grantPermissionsMethod = "grantPermissions";
}
else {
grantPermissionsMethod = "grantPermissionsLPw";
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
XposedBridge.log("[WARNING] THIS HOOK IS NOT GUARANTEED TO WORK ON ANDROID VERSIONS PRIOR TO JELLYBEAN");
}
}
XposedBridge.hookAllMethods(XposedHelpers.findClass("com.android.server.pm.permission.PermissionManagerService", lpparam.classLoader),
grantPermissionsMethod, new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
// on Android R and above, param.args[0] is an instance of android.content.pm.parsing.ParsingPackageImpl
// on Android Q and older, param.args[0] is an instance of android.content.pm.PackageParser$Package
// However, they both declare the same fields we need, so no need to check for class type
String pkgName = (String) XposedHelpers.getObjectField(param.args[0], "packageName");
XposedBridge.log("Package " + pkgName + " is requesting permissions");
if (pkgName.equals(targetPkgName)) {
List<String> permissions = (List<String>) XposedHelpers.getObjectField(param.args[0], "requestedPermissions");
for (String newPermission: newPermissions) {
if (!permissions.contains(newPermission)) {
permissions.add(newPermission);
XposedBridge.log("Added " + newPermission + " permission to " + pkgName);
}
}
}
}
});
Notes:
You must check System Framework in LSposed Manager
A reboot is required after adding the target permissions
You still need to prompt the user to accept sensitive permissions (ie android.permission.READ_CONTACTS), even if you have added them using this method
Wow, thx. Great for the install permissions!
I wrote a class to grant install and runtime/sensitive permissions (without prompting users).
Android 12 and 13 implementation:
Java:
public class Grant_Package_Permissions {
private static final int sdk = android.os.Build.VERSION.SDK_INT;
public static void hook(LoadPackageParam lpparam) {
try {
Class<?> PermissionManagerService = XposedHelpers.findClass(
sdk >= 33 /* android 13+ */ ?
"com.android.server.pm.permission.PermissionManagerServiceImpl" :
"com.android.server.pm.permission.PermissionManagerService", lpparam.classLoader);
Class<?> AndroidPackage = XposedHelpers.findClass(
"com.android.server.pm.parsing.pkg.AndroidPackage", lpparam.classLoader);
Class<?> PermissionCallback = XposedHelpers.findClass(
sdk >= 33 /* android 13+ */ ?
"com.android.server.pm.permission.PermissionManagerServiceImpl$PermissionCallback" :
"com.android.server.pm.permission.PermissionManagerService$PermissionCallback", lpparam.classLoader);
// PermissionManagerService(Impl) - restorePermissionState
XposedHelpers.findAndHookMethod(PermissionManagerService, "restorePermissionState",
AndroidPackage, boolean.class, String.class, PermissionCallback, int.class, new XC_MethodHook() {
@SuppressWarnings("unchecked")
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
// params
Object pkg = param.args[0];
int filterUserId = (int) param.args[4];
// obtém os campos
Object mState = XposedHelpers.getObjectField(param.thisObject, "mState");
Object mRegistry = XposedHelpers.getObjectField(param.thisObject, "mRegistry");
Object mPackageManagerInt = XposedHelpers.getObjectField(param.thisObject, "mPackageManagerInt");
// Continua ?
String packageName = (String) XposedHelpers.callMethod(pkg, "getPackageName");
Object ps = XposedHelpers.callMethod(mPackageManagerInt,
sdk >= 33 /* android 13+ */ ?
"getPackageStateInternal" :
"getPackageSetting", packageName);
if (ps == null)
return;
int[] getAllUserIds = (int[]) XposedHelpers.callMethod(param.thisObject, "getAllUserIds");
int userHandle_USER_ALL = XposedHelpers.getStaticIntField(Class.forName("android.os.UserHandle"), "USER_ALL");
final int[] userIds = filterUserId == userHandle_USER_ALL ? getAllUserIds : new int[]{filterUserId};
for (int userId : userIds) {
List<String> requestedPermissions;
Object userState = XposedHelpers.callMethod(mState, "getOrCreateUserState", userId);
int appId = (int) XposedHelpers.callMethod(ps, "getAppId");
Object uidState = XposedHelpers.callMethod(userState, "getOrCreateUidState", appId);
// package 1
if (packageName.equals("PACKAGE_1")) {
requestedPermissions = (List<String>) XposedHelpers.callMethod(pkg, "getRequestedPermissions");
grantInstallOrRuntimePermission(requestedPermissions, uidState, mRegistry,
Manifest.permission.RECORD_AUDIO);
grantInstallOrRuntimePermission(requestedPermissions, uidState, mRegistry,
Manifest.permission.MODIFY_AUDIO_SETTINGS);
}
// package 2
if (packageName.equals("PACKAGE_2")) {
requestedPermissions = (List<String>) XposedHelpers.callMethod(pkg, "getRequestedPermissions");
grantInstallOrRuntimePermission(requestedPermissions, uidState, mRegistry,
Manifest.permission.READ_CONTACTS);
}
}
}
});
} catch (Exception e) {
XposedBridge.log(e);
}
}
private static void grantInstallOrRuntimePermission(List<String> requestedPermissions, Object uidState,
Object registry, String permission) {
if (!requestedPermissions.contains(permission))
XposedHelpers.callMethod(uidState, "grantPermission",
XposedHelpers.callMethod(registry, "getPermission", permission));
}
}
Edit: Android 12 and 13 implementation!
this looks promising. how to use this in xposed ? is there a module available?